I have to calculate how many years passed between two dates. My code works fine - except for very specific dates.
The code bellow should produce the same year difference for both dateEnd and dateEnd1, however they are not equal. If I would change year from 2003 to 2004, it would become equal. If I would leave the year, but change from march to february, it would again be equal.
I guess it has something to do with leap years, but I am clueless why? Especially since there were 4 leap years in that period, but the year miscalculation happens for dates which are one day apart only.
I expect year difference to be 12 in both of these cases, however I get 13 in the first case with the dateEnd variable
var dateStart = '2003,03,11';
var dateEnd = '2016,03,10';
var dateEnd1 = '2016,03,09';
var difference = (new Date(dateEnd)).getTime() - (new Date(dateStart)).getTime();
difference = (new Date(difference)).getFullYear() - 1970;
alert('Between ' + dateStart + ' and ' + dateEnd + ' elapsed ' + difference + ' years.');
difference = (new Date(dateEnd1)).getTime() - (new Date(dateStart)).getTime();
difference = (new Date(difference)).getFullYear() - 1970;
alert('Between ' + dateStart + ' and ' + dateEnd1 + ' elapsed ' + difference + ' years.');
Here is the code on jsfiddle. One person in the comments managed to reproduce the problem on his jsfiddle!
Here are values of variables I get
dateStart time: 1047337200000
dateEnd time: 1457564400000
dateEnd1 time: 1457478000000
Time difference for the first case: 410227200000
Between 2003,03,11 and 2016,03,10 elapsed 13 years.
Time difference for the second case: 410140800000
Between 2003,03,11 and 2016,03,09 elapsed 12 years.
The can/cannot reproduce difference is not the locale, but the time zone. For me (in California), the above values give:
alert(new Date(410140800000)); // "Thu Dec 30 1982 16:00:00 GMT-0800 (Pacific Standard Time)"
alert(new Date(410227200000)); // "Fri Dec 31 1982 16:00:00 GMT-0800 (Pacific Standard Time)"
Were I at or east of GMT, the second date would be "Sat Jan 1 1983...", giving the different number of years. Leap years are probably coming into it because the number of leap years is affecting the number of days in the difference.
I thought you would see the same thing if you use 2005/2018, but as Arjan points out, it's not quite that simple and does indeed involve leap years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With