Reputation: 387
I want to get the difference between two dates in days, hours and minutes. I tried to do this using the ms from January 1st 1970 like this:
var d = new Date()
daydiff = ~~((d.getTime()-(Date.parse(SavedReminders[i][7]))) / 86400000);
hourdiff = ~~((d.getTime() - (Date.parse(SavedReminders[i][7]))) / 3600000);
mindiff = ~~((d.getTime() - (Date.parse(SavedReminders[i][7]))) / 60000);
where SavedReminders[i][7] = 2015-04-06T17:34:00
However this gives some weird results, if i test it in the same hour (5pm) then it seems to work, but when it becomes 6pm or 7pm i start getting incorrect results, as if it's not taking account of hours.
For example when the current time is '2015-04-06T19:26:00' and i run this code it gives the results:
d.getTime() = 1428344775364
Date.parse(SavedReminders[i][7] = 1428341640000
daydiff = 0
hourdiff = 0
mindiff = 52
Upvotes: 1
Views: 84
Reputation: 3997
Possible integer overflow issue using the ~~ this technique with very large numbers? (there is no telling how many decimal points to the right the divide operation generates...)
Do you get the same errors when you use the traditional Math.floor?
daydiff = Math.floor((d.getTime()-(Date.parse(SavedReminders[i][7]))) / 86400000);
Upvotes: 0
Reputation: 1553
Both getTime() and Date.parse return milliseconds from 1/1/1970 in UTC time, but you are not declaring both in utc time. So timezones are going to alter what you are comparing.
In other words, if it's 3pm local time and 7pm UTC time, and you run that code, when you get a new Date() you are actually saying it's 7pm UTC time, so when you put in a string that indicates it's 7pm without a timezone, it's interpreting that as 7pm as well. The end result is you have a 0 hour difference, because the original dates were in different time zones but indicating the same time once converted to UTC.
Hopefully that makes sense... handling datetime values is a nightmare in every programming language and doubly so in javascript. If possible, I recommend a good javascript date library like moment.js.
Upvotes: 1