BigBug
BigBug

Reputation: 6290

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.

Upvotes: 14

Views: 32536

Answers (2)

timrwood
timrwood

Reputation: 10681

I wrote a lightweight date library called Moment.js to handle stuff like this.

var birthday = moment('12/02/1987', 'MM-DD-YYYY');
var inputDate = moment(element.value, 'MM-DD-YYYY');
var diff = birthday.diff(inputDate, 'days'); 

http://momentjs.com/docs/#/displaying/difference/

Upvotes: 142

gilly3
gilly3

Reputation: 91657

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

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

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

Upvotes: 11

Related Questions