Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  115] [ 7]  / answers: 1 / hits: 55191  / 11 Years ago, fri, august 2, 2013, 12:00:00

I need to write JavaScript that's going to allow me to compare two ISO timestamps and then print out the difference between them, for example: 32 seconds.



Below is a function I found on Stack Overflow, it turns an ordinary date into an ISO formatted one. So, that's the first thing out the way, getting the current time in ISO format.



The next thing I need to do is get another ISO timestamp to compare it with, well, I have that stored in an object. It can be accessed like this: marker.timestamp (as shown in the code below). Now I need to compare those two two timestamps and work out the difference between them. If it's < 60 seconds, it should output in seconds, if it's > 60 seconds, it should output 1 minute and 12 seconds ago for example.



Thanks!



function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}

var date = new Date();
var currentISODateTime = ISODateString(date);
var ISODateTimeToCompareWith = marker.timestamp;

// Now how do I compare them?

More From » javascript

 Answers
8

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

[#76552] Friday, August 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anais

Total Points: 672
Total Questions: 118
Total Answers: 121

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;