简体   繁体   中英

Javascript Date.getTime function doesn't return the correct value or I'm doing something wrong

I'm trying to calculate timestamp for a given date (hour and minute is not important for now) .
I'm not looking for calculating days between two dates but as a sample of problem with computed timestamp lets take a look at the following snippet which calculate the days between two date :

console.log(((new Date(2017,2,10)).getTime() - (new Date(2017,1,31)).getTime())/86400000);

this snippet print 7 for me while if I did the math correctly it actually should prints 10 . I know there is something wrong with my code but I don't know what is it.

Months in the Date constructor are 0-indexed, so 0 is January, 1 is February, etc. and moreover the parameters can overflow ( new Date(2017,11,32) is actually Mon Jan 01 2018 00:00:00 ). So in your example the dates are in fact:

new Date(2017,1,31)
Fri Mar 03 2017 00:00:00
new Date(2017,2,10)
Fri Mar 10 2017 00:00:00

Therefore the result is correct.

The value being returned in your code is absolutely fine. According to the Javascript MDN Documentation , for the Month parameter in the function, you can pass the following allowed values, otherwise they are automatically adjusted-

Integer value representing the month, beginning with 0 for January to 11 for December.

So, in your case, since 31 February 2017 doesn't exist, the Date object is automatically adjusted and initialized with a value of 03 March 2017 . And the other date is initialised with a value of 10 March 2017 . Thus, the difference is coming correctly as 7 days. Here is a short note on the adjustment from MDN documentation-

Where Date is called as a constructor with more than one argument, if values are greater than their logical range (eg 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. Eg new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM