Search code examples
javascriptdatedatediff

JS Date API: Diff between two dates in hours – Odd behaviour with current Date


I know this is a basic question that may have been answered before, but I've been scratching my head about this one. So here it is:

I want to get the number of hours between a set date and the current time.

I have attempted the following (this was done on 2018/05/23 21:35 UTC-4:00):

(new Date(2018, 05, 24).getTime() - new Date(2018,05,23).getTime())/(3600*1000) // 24

(new Date(2018, 05, 24).getTime() - new Date().getTime())/(3600*1000) // 746.4949...

Oddly, subtracting tomorrow from current time gives 746 hours. The expectation is that I would have gotten ~2.4h. I also attempted the following variations:

// Straight up dates

(new Date(2018, 05, 24) - new Date(2018,05,23))/(3600*1000) // 24

(new Date(2018, 05, 24) - new Date())/(3600*1000) // 746.4949...

// Using valueOf

(new Date(2018, 05, 24).valueOf() - new Date(2018,05,23).valueOf())/(3600*1000) // 24

(new Date(2018, 05, 24).valueOf() - new Date().valueOf())/(3600*1000) // 746.4949...

// Using Date.now()

(new Date(2018, 05, 24).valueOf() - new Date().now())/(3600*1000) // 746.4949...

Any idea why this is a problem, and how to solve it?

Thanks a lot!


Solution

  • Month numbers in Javascript dates are zero-based, so new Date(2018, 05, 24) is June 24, 2018, not May 24, 2018. Subtract 1 from the month number to get the result you expect.

    console.log((new Date(2018, 4, 24).getTime() - new Date().getTime())/(3600*1000))

    This prints about 2.14 when I run it at May 23 21:50 UTC-04:00.