在JS中比较两个日期 [英] Compare two dates in JS
本文介绍了在JS中比较两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将用户的生日与今天的日期进行比较,并得到其间的天数。他们输入的生日将以 类型的输入框中以 12/02/1987 的形式
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
在我的JS文件中,我有如下代码:
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;
}
而不是使用圣诞节我想比较 element.value
...我该怎么做?
Instead of using "Christmas" I want to compare element.value
... how do I do this?
当我把 difference = today - element.value
它不会显示我的区别。警报框出现为 NaN
。
When I put difference = today - element.value
it won't show me the difference. The alert box comes up as NaN
.
推荐答案
您需要首先将 element.value
日期:
difference = today - new Date(element.value);
http://jsfiddle.net/gilly3/3DKfy/
这篇关于在JS中比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文