Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...