Compare 2 ISO 8601 timestamps and output seconds/minutes difference

I'd recommend getting the time in seconds from both timestamps, like this:

// currentISODateTime and ISODateTimeToCompareWith are ISO 8601 strings as defined in the original post
var firstDate = new Date(currentISODateTime),
    secondDate = new Date(ISODateTimeToCompareWith),
    firstDateInSeconds = firstDate.getTime() / 1000,
    secondDateInSeconds = secondDate.getTime() / 1000,
    difference = Math.abs(firstDateInSeconds - secondDateInSeconds);

And then working with the difference. For example:

if (difference < 60) {
    alert(difference + ' seconds');
} else if (difference < 3600) {
    alert(Math.floor(difference / 60) + ' minutes');
} else {
    alert(Math.floor(difference / 3600) + ' hours');
}

Important: I used Math.abs to compare the dates in seconds to obtain the absolute difference between them, regardless of which is earlier.


I would just store the Date object as part of your ISODate class. You can just do the string conversion when you need to display it, say in a toString method. That way you can just use very simple logic with the Date class to determine the difference between two ISODates:

var difference = ISODate.date - ISODateToCompare.date;
if (difference > 60000) {
  // display minutes and seconds
} else {
  // display seconds
}

Comparing two dates is as simple as

var differenceInMs = dateNewer - dateOlder;

So, convert the timestamps back into Date instances

var d1 = new Date('2013-08-02T10:09:08Z'), // 10:09 to
    d2 = new Date('2013-08-02T10:20:08Z'); // 10:20 is 11 mins

Get the difference

var diff = d2 - d1;

Format this as desired

if (diff > 60e3) console.log(
    Math.floor(diff / 60e3), 'minutes ago'
);
else console.log(
    Math.floor(diff / 1e3), 'seconds ago'
);
// 11 minutes ago

Tags:

Javascript