Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 308
BigBug Avatar asked Nov 02 '11 23:11

BigBug


1 Answers

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/

like image 95
timrwood Avatar answered Oct 05 '22 23:10

timrwood