I have a date and time in the format of 2029-11-26T23:59:59
. I want to get its difference compared to today's date and time. The Date()
function in javascript is a different format in comparison to the date I have. What's the best way to do it?
Asked
Active
Viewed 59 times
1

mha
- 551
- 2
- 11
- 22
-
You want the difference in what format? Days? Minutes? Hours? Milliseconds? – Jeff Dec 16 '19 at 14:28
1 Answers
3
Difference between 2 date/time instances could mean a lot of things - you might want to know the number of seconds, minutes, hours, days, weeks, months or years between those 2 instances.
You can simply convert your date/time string of the format 2029-11-26T23:59:59
using the Date()
function, from where you can find out its difference from the current time.
The following function would give you the difference between the 2 times in milliseconds:
function timeDifference(myDateString) {
var currentDate = new Date();
var myDate = new Date(myDateString);
return myDate.getTime() - currentDate.getTime();
}
From here, you can convert this difference into any unit - be it minutes, hours, days, months or years. Simply divide the time in milliseconds with the right number. A few examples are shown below:
var myDateString = '2029-11-26T23:59:59';
var oneDayInMilliseconds = 1000 * 60 * 60 * 24;
var oneYearInMilliseconds = oneDayInMilliseconds * 365;
var differenceInDays = timeDifference(myDateString) / oneDayInMilliseconds;
var differenceInYears = timeDifference(myDateString) / oneYearInMilliseconds;

Pranjal Nadhani
- 106
- 1
- 5
-
-
That's a good point @Jeff. If there's a requirement to deal with different time zones, we can convert the dates into UTC and then do the calculation in the function `timeDifference`. – Pranjal Nadhani Dec 16 '19 at 15:01
-
-
Parsing of strings with the built–in parser is strongly recommended against, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). 2029-11-26T23:59:59 *should* be parsed as local but Safari parses it as UTC. The method used for getting the difference in days is poor, there are [much better answers](https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript). – RobG Dec 16 '19 at 21:43