Search code examples
javascriptdatesubtraction

Date subtraction in JavaScript


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?


Solution

  • 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) { 
         ...
    }