Adeno 有一个有效的答案,但如果日期是毫秒,则会失败(如果您使用有效的日期字符串,则在 OP 的示例中不是这种情况)。为确保您按分钟或天数比较日期,您可以执行以下操作:
function sameTime(dt1,dt2){
//round the dates to the minutes
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setSeconds(0,0);
t2.setSeconds(0,0);
return t1.toString()===t2.toString();
}
function sameDay(dt1,dt2){
//round the dates to the day
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setHours(0,0,0,0);
t2.setHours(0,0,0,0);
return t1.toString()===t2.toString();
}
function sameMonth(dt1,dt2){
//round the dates to the month
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setHours(0,0,0,0);
t2.setHours(0,0,0,0);
t1.setDate(1);
t2.setDate(1);
return t1.toString()===t2.toString();
}
var date1 = "2013-07-08T12:30:00",
date2 = "2013-07-08T13:30:00";
var d1 = new Date(date1);
var d2 = new Date(date2);
console.log(sameTime(d1,d2));//precise to the minute
console.log(sameDay(d1,d2));//precise to the day
console.log(sameMonth(d1,d2));//precise to the month