calculating time difference in iso time format in javascript?

Viewed 6073

I have two date string in ISO format. I am calculating the minutes difference between them using moment js.

var currenttime  =  new Date().toISOString();
var expiretime  = '2020-06-05T12:18:33.000Z';


let minutes = moment(expiretime, 'YYYY-MM-DD[T]HH:mm:ss. SSS[Z]').diff(moment(currenttime, 'YYYY-MM-DD[T]HH:mm:ss. SSS[Z]'), 'minutes');


console.log(minutes)

Now i have two questions

  1. Is this is the best way to calculate the minutes difference ?

  2. When i run new Date().toISOString() the value before z is the supposed to be the timezone but on every restart it changes ?

Please let me know what is the issue ?

2 Answers

I don't think you have to include moment for this purpose only, this can be done in ordinary Javascript. To calculate time difference just subtract the two timestamps which will give the difference in milliseconds. Then divide by 60*1000 which will give the time difference in minutes.

let currentTime = new Date();
let expireTime = new Date('2020-06-05T12:18:33.000Z');

let minutes = (expireTime - currentTime) / (1000 * 60);

console.log(minutes);

For your first question, what you can do is simply subtract the two dates (date objects and not strings) ,

Newer date - Older date ( this will give the result in milliseconds)

or use Math.abs() function to calculate milliseconds -

var msec = Math.abs( currenttime - expiretime );

and convert this to minutes using -

var min = Math.floor((msec/1000)/60);

2) Z in the datetime string stands for Zulu, it indicates that the time is in UTC format. You can simply subtract two date objects.

var currenttime = new Date();
var currenttime_UTC = currenttime.getUTCDate();
var expiretime = new Date('2020-06-05T12:18:33.000Z');

var msec = Math.abs( currenttime_UTC - expiretime );
var min = Math.floor((msec/1000)/60);
Related