BigBug BigBug - 5 months ago 9
HTML Question

Compare two dates in JS

I want to compare the user's birthday against today's date and get the number of days in between. The birthday they enter will be in the form of 12/02/1987 in an input box of type text

In my JS file I have code that looks like this:

function validateDOB(element) {
var valid = false;

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //do that January is NOT represented by 0!
var yyyy = today.getFullYear();

if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}

var today = mm + '/' + dd + '/' + yyyy;
alert(today);
if (element.value != today) {
var days = 0;
var difference = 0;

Christmas = new Date("December 25, 2011");

today = new Date();

difference = today - Christmas

days = Math.round(difference / (1000 * 60 * 60 * 24)-1);
alert(days);
valid = true;
}


Instead of using "Christmas" I want to compare
element.value
... how do I do this?

When I put
difference = today - element.value
it won't show me the difference. The alert box comes up as
NaN
.

Answer

You'll need to first parse element.value as a date:

difference = today - new Date(element.value);

http://jsfiddle.net/gilly3/3DKfy/

Comments