Javascript 比较JS中的两个日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7988525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:17:29  来源:igfitidea点击:

Compare two dates in JS

javascripthtmlformsdate

提问by BigBug

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/1987in an input box of type text

我想将用户的生日与今天的日期进行比较,并获得两者之间的天数。他们输入的生日将以12/02/1987的形式出现文本类型的输入框中

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

在我的 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;
}

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

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

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

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

采纳答案by gilly3

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

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

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

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

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

回答by timrwood

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

我编写了一个名为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/

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