有几件事要考虑。
当您从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
当创建一个字符串的新的Date对象,使用格式日期:'YYYY-MM-DD '以避免地区信息的问题。 (即:'新日期('2014-09-02');')。 – melancia 2014-09-02 10:58:46