0

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!

Philippe Hebert
  • 1,616
  • 2
  • 24
  • 51

2 Answers2

3

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

As mentioned on MDN

Note: The argument month is 0-based. This means that January = 0 and December = 11.

The simplest way to get the difference between two dates on hours, (ref)

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds' difference into hours.

Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40