我正在比较 2 个日期
1) 2013-12-18
2) 2013-12-4
我的代码认为 2013-12-4 大于 2013-12-18。
这是我的代码演示:http://jsfiddle.net/tdVGL/
这是我的 JavaScript 代码:
var date = new Date();
var getFromDate =
parseInt(date.getFullYear()) + '-' +
parseInt(date.getMonth() + 1) + '-' +
parseInt(date.getDate() - 14);
var newDate = new Date();
var newD = parseInt(newDate.getDate());
var newM = parseInt(newDate.getMonth() + 1);
var newY = parseInt(newDate.getFullYear());
var myDate = parseInt(newY) + '-' + parseInt(newM) + '-' + parseInt(newD);
alert(getFromDate);
alert(myDate);
if (getFromDate < myDate) {
alert("Sorry! You cannot add event on past dates.");
return false;
} else {
alert("This is the right day");
}
最佳答案
您比较的不是日期比较。这些值被视为字符串。看看这个对比。您需要将它们转换为有效的 Date 对象以进行正确的日期比较。
if (new Date(getFromDate) < new Date(myDate)) {
alert("Sorry! You cannot add event on past dates.");
return false;
}
else {
alert("This is the right day");
}
关于javascript - JavaScript 中的日期比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20651949/