2014-09-02 115 views
0

我尝试验证用户输入的日期。它必须是今天或晚些时候。我该怎么做?JavaScript简单日期验证

为什么在下面的代码中的条件是false

var today = new Date(); 
var idate = new Date('02/09/2014'); 

if(today > idate) { 
    alert('your date is big'); 
} 

如果我设置today那么今天的日期,也是我传递idate那么它也是今天的日期,那么我该怎么比较日期?

这里的jsfiddle:http://jsfiddle.net/0osh0q8a/1/

+1

当创建一个字符串的新的Date对象,使用格式日期:'YYYY-MM-DD '以避免地区信息的问题。 (即:'新日期('2014-09-02');')。 – melancia 2014-09-02 10:58:46

回答

1

有几件事要考虑。

当您从string表示创建新对象Date时,请使用格式YYYY-MM-DD。这将避免区域设置的问题。

比较两个日期时,如果时间可以被忽略,则将两者设置为完全相同的时间。这里看起来就是这种情况。

最后,使用Date.parse()来确保您的对象是有效的日期并且可以进行比较。

var today = new Date(); 
var idate = new Date('2014-09-02'); 
// The date entered by the user will have the same 
// time from today's date object. 
idate.setHours(today.getHours()); 
idate.setMinutes(today.getMinutes()); 
idate.setSeconds(today.getSeconds()); 
idate.setMilliseconds(today.getMilliseconds()); 

// Parsing the date objects. 
today = Date.parse(today); 
idate = Date.parse(idate); 

// Comparisons. 
if (idate == today) { 
    alert('Date is today.'); 
} 
else if (idate < today) { 
    alert('Date in the past.'); 
} 
else if (idate > today) { 
    alert('Date in the future.'); 
} 

Demo

作为一个方面说明,当你面对难以解决的日期/时间计算,操作等,可以使用Moment.js库。这是非常有用的:Moment.js

0

默认数据解析器读取你的idate作为第九febuary 2014年,因此todayidate

更大如果设置IDATE到2014年9月4日的代码运行作为预计

var today = new Date(); 
var idate = new Date('09/04/2014'); 

console.log(today); 
>>>Tue Sep 02 2014 11:48:52 GMT+0100 (BST) 
console.log(idate); 
>>>Thu Sep 04 2014 00:00:00 GMT+0100 (BST) 
0

您有2个问题。

日期文化和时间部分。

首先,new Date()接收当前浏览器的文化加上时间部分的当前日期。

new Date('09/04/2014')不添加时间部分,所以它开始于00:00:00和文化再次取决于浏览器。所以它可能意味着9月3日9日或4日取决于文化。

0

请记住,该new Date()包含时间部分。 如果你不关心的时间,创造了今天的日期是这样的:

var now = new Date(); 
var today = new Date(now.getFullYear(), now.getMonth(), now.getDay()); 

另一件事是,JS的日期格式为“MM/DD/YYYY”。因此,改变你的“IDATE”是这样的:

var idate = new Date('09/02/2014'); 

您可以使用<and>比较的日期。但==将始终返回false,检查2个日期是平等的利用:if(today.getTime() == idate.getTime()) 请参阅更新的小提琴:http://jsfiddle.net/0osh0q8a/3/