Difference between start date and end date with Moment js

Asked

Viewed 4,339 times

3

I need to inform how much time I have of a certain chronometer, I have the date of the moment at which I started the event.

I’m developing with angular 4 typescript and use plugin Moment js

In my html I’m doing so:

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

The restultado that is printed on the screen is being:

-62.444583333333334

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

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

An important point is that I cannot use the date of my computer due to the time of the server and the client pc may be outdated. To solve this problem from time to time I send a location that contains an hour also from the server.

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

I am thinking of making the final date (in the case I sent the location) - the initial date, in order to obtain the time that is in route.

I don’t know if I can do this with Moment js, but I need to do this, how can I ?

Is there any plugin that facilitates, or even javascript native that solves my problem.

  • Do you really want to know how you make that difference and how you convert to, I don’t know, hours, minutes and seconds? Or do you really need the timing? Thousandths?

  • No milliseconds no matter, I only need hours minutes and seconds,

  • @Joseph has achieved something.

2 answers

2

There is the function diff 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

1


One can use Date() to solve the problem. Simply create a new object with the desired start time (and finish time) and make a new Date() with the difference. Then access hours, minutes, seconds and milliseconds separately with the accompanying methods Date() to format the way you want. Take 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 );

  • I can do this at runtime using typescript ?

  • @Renanrodrigues yes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.