Difference between start date and end date with moment js

3

I need to tell you how much time I have for a certain timer, I have the date from which I started the event.

I'm developing with angular 4 typescript and I use plugin moment js

In my html I'm doing this:

<div class="row card-indicator centralize-text">
  {{((locations[indiceMotorist]?.trip.createdAt == undefined)? '0' : locations[indiceMotorist]?.trip.createdAt) | amDifference: today :'minutes' : true }}
</div>

The content that is printed on the screen is:

  

-62.444583333333334

My date is in this format, and it comes from my server:

createdAt: "2017-11-01T13:13:59.015Z"

One important point is that I can not use the date on my computer because the server's time and the client's pc can be out-of-date. To solve this problem from time to time I send a location that also contains a time from the server.

createdAt: "2017-11-01T14:22:23.466Z"

I'm thinking of making the end date (in the case I told you of the location) - the start date, in order to get the time that is in progress.

I do not know if I can do this with moment js, but I need to do this, how can I get it?

There is a plugin that makes it easy, or even% native, to solve my problem.

    
asked by anonymous 01.11.2017 / 15:26

2 answers

1

You can use Date() to solve the problem. Just create a new object with the desired start and end time and make a new Date() with the difference. Then access hours, minutes, seconds, and milliseconds separately with the methods that accompany Date() to format the way you want. See an example :

// Usar como argumento as datas recuperadas do servidor
var inicio = new Date("2017-11-01T13:13:59.015Z");
var fim = new Date("2017-11-01T14:22:23.466Z");

// A diferença "d" de datas bruta retorna como milissegundos (inteiro)
var d = new Date( fim - inicio );

// Mostrando:
tempo =  d.getUTCHours() + "h ";
tempo += d.getUTCMinutes() + "m ";
tempo += d.getUTCSeconds() + "s ";
tempo += d.getUTCMilliseconds() + "ms";

console.log( tempo );
    
01.11.2017 / 16:57
1

There is the diff function of moment .

var antes = moment("2017-11-01T13:13:59.015Z");
var depois= moment("2017-11-01T14:22:23.466Z');

var horas = depois.diff(antes, 'hours');
var minutos = depois.diff(antes, 'minutes');
var segundos= depois.diff(antes, 'seconds');

var diferenca = '${horas}:${minutos}:${segundos}'

Fiddle

    
02.11.2017 / 13:09