user656523 user656523 - 1 year ago 132
Javascript Question

Date subtraction in JavaScript

I have two text boxes which accept

Start Date
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
and End Date as

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
, instead of
.What am I doing wrong?

Answer Source

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) { 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download