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
Compare two dates in JS
提问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.value
it 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.value
as a date:
您需要首先解析element.value
为日期:
difference = today - new Date(element.value);
回答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');