Compare 2 ISO 8601 timestamps and second / minute difference

I need to write JavaScript that allows me to compare two ISO timestamps and then print the difference between them, for example: "32 seconds".

Below is the function I found in Stack Overflow, it turns a regular date into a formatted ISO. So, the first thing to do is get the current time in ISO format.

The next thing I need to do is get another ISO timestamp to compare it, well, I have what is stored in the object. It can be accessed as follows: marker.timestamp (as shown in the code below). Now I need to compare these two timestamps and work out the difference between them. If it is & lt; 60 seconds, it should be displayed in seconds, if it is> 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? 
+6
source share
3 answers

Comparing two dates is as easy as

 var differenceInMs = dateNewer - dateOlder; 

So convert timestamps to 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 it as you like

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

I would just save the Date object as part of your ISODate class. You can simply convert the string when you need to display it, say, in the toString method. Thus, you can simply use very simple logic with the Date class to determine the difference between the two ISODates:

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

I would recommend getting the time in seconds from both timestamps, for example:

 var firstDate = new Date(currentISODateTime), secondDate = new Date(ISODateTimeToCompareWith), firstDateInSeconds = firstDate.getTime() * 1000, secondDateInSeconds = secondDate.getTime() * 1000, difference = Math.abs(firstDateInSeconds - secondDateInSeconds); 

And then we work with difference . For instance:

 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 dates in seconds to get the absolute difference between them, regardless of what happened before.

+1
source

Source: https://habr.com/ru/post/950927/


All Articles