首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >日期比较在javascript中失败

日期比较在javascript中失败
EN

Stack Overflow用户
提问于 2013-12-18 07:24:02
回答 3查看 62关注 0票数 0

我在比较两次约会

1) 2013-12-18

2) 2013年-12-4

我的代码考虑的是2013-12-4比2013-12-18要大。

下面是我的代码演示:http://jsfiddle.net/tdVGL/

这是我的JavaScript代码:

代码语言: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");
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-18 07:28:42

你要比较的不是日期比较。这些值被视为字符串。看看这个比较。为了进行正确的日期比较,您需要将它们转换为有效的Date对象。

代码语言:javascript
复制
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");
}

Js Fiddle演示

票数 2
EN

Stack Overflow用户

发布于 2013-12-18 07:34:19

正如Sachim所说,您只是在字符串上进行比较,而不是在Date对象上进行比较。

您可以简化代码(只对Date对象工作)

代码语言:javascript
复制
var myDate     = new Date();                
var getFromDate = new Date(myDate);
getFromDate.setDate(myDate.getDate() -14);

alert(getFromDate);//of course, this is not in the format yyyy-mm-dd
alert(myDate);

if(getFromDate<myDate)
{
    alert("Sorry! You cannot add event on past dates.");
    return false;
}
else
{
     alert("This is the right day");
}
票数 1
EN

Stack Overflow用户

发布于 2013-12-18 07:33:28

您要比较的对象不是日期,而是字符串。

代码语言:javascript
复制
var getFromDate = parseInt(date.getFullYear())+'-'+parseInt(date.getMonth()+1)+'-'+parseInt(date.getDate()-14);

您可以将新日期实例化为

new Date(getFromDate)new Date(myDate)

然后再做比较

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20651949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档