JavaScript date subtraction

I have two text fields that accept Start Date, End Daterespectively, in the format YYYY / MM / DD.

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

Here is what I still have:

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;
}

As an example, when I select Start Date as 2012/01/22and End Date as2012/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 - startDateis equal 3283200000instead 38. What am I doing wrong?

+5
source share
2 answers

3283200000 is 38 days in milliseconds.

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

In addition, there are 38 days between the two dates, not 39.

, ( ), :

var days = 24*60*60*1000;

"" :

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

Jeff B - . startDate, , 31 , endDate - 20 , , , 50 1 , 50 . , - .

Date , , .

, , , , , -. , ; .

. - , , . , .

0

All Articles