Date subtraction in JavaScript

橙三吉。 提交于 2020-01-14 09:46:05

问题


I have two text boxes which accept Start Date and End Date respectively, in format YYYY/MM/DD.

I need to alert the user if he selects an end date that exceeds the start date by 50 days.

Here's what I have so far:

var startDate = new Date(document.getElementsByName('MYSTARTDATE').value);
var endDate = new Date(document.getElementsByName('MYENDDATE').value);
if ((endDate - startDate) > 50) 
{
    alert('End date exceeds specification');
    return false;
}

Just as an example, when I select Start Date as 2012/01/22 and End Date as 2012/02/29

startDate = 'Sun Jan 22 00:00:00 UTC +0530 2012'
endDate = 'Wed Feb 29 00:00:00 UTC +0530 2012'

And the result for endDate - startDate is 3283200000, instead of 38.What am I doing wrong?


回答1:


3283200000 is 38 days in milliseconds.

38 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds

Also, there are 38 days between those two dates, not 39.

An easy solution is to have a variable (constant really) defined as the number of milliseconds in a day:

var days = 24*60*60*1000;

And use that variable as a "unit" in your comparison:

if ((endDate - startDate) > 50*days) { 
     ...
}



回答2:


The solution by Jeff B is incorrect, because of daylight savings time. If the the startDate is, say, on October 31, and the endDate is on December 20, the amount of time that has actually elapsed between those two times is 50 days plus 1 hour, not 50 days. This is especially bad if your program doesn't care about the time of day and sets all times at midnight - in that case, all calculations would be off by one for the entire winter.

Part of the correct way to subtract dates is to instantiate a new Date object for each of the times, and then use an Array with the number of days in each month to compute how many days have actually passed.

But to make things worse, the dates that Europe changes the clocks are different than the dates that the clocks are changed in New York. Therefore, timezone alone is not sufficient to determine how many days have elapsed; location is also necessary.

Daylight savings time adds significant complexity to date handling. In my website, the function needed to accurately compute the number of days passed is nearly a hundred lines. The actual complexity is dependent on whether the calculations are client side or server side or both and who is viewing the data.



来源:https://stackoverflow.com/questions/9495043/date-subtraction-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!