比较JS中的两个日期

时间:2011-11-02 23:20:21

标签: javascript html forms date

我想将用户的生日与今天的日期进行比较,并获取介于两者之间的天数。他们输入的生日将以 12/02/1987 的形式出现在 text

类型的输入框中

在我的JS文件中,我的代码如下所示:

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;
}

我没有使用“圣诞节”,而是想比较element.value ...我该怎么做?

当我放difference = today - element.value时,它不会告诉我差异。警报框显示为NaN

2 个答案:

答案 0 :(得分:141)

我写了一个名为Moment.js的轻量级日期库来处理这样的事情。

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/

答案 1 :(得分:12)

您需要先将element.value解析为日期:

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

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