Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 921
user656523 Avatar asked Feb 29 '12 07:02

user656523


People also ask

How do you subtract days in JavaScript?

You can use d. setDate(d. getDate() + days) with both positive and negative values for days to add and subtract days respectively.

How do you subtract days from a date?

Add or subtract days from a date Enter your due dates in column A. Enter the number of days to add or subtract in column B. You can enter a negative number to subtract days from your start date, and a positive number to add to your date. In cell C2, enter =A2+B2, and copy down as needed.

How do you sum dates in JavaScript?

var today = new Date(); var tomorrow = new Date(); tomorrow. setDate(today. getDate()+1);


1 Answers

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) { 
     ...
}
like image 62
Jeff B Avatar answered Sep 20 '22 01:09

Jeff B