我们可以通过比较两个日期对象的年、月、日属性来实现日期的比较。新建两个日期对象,并将它们的时分秒属性都设置为 0,这样就可以将两个日期对象的比较转化为年月日的比较。
以下是代码示例:
const date1 = new Date('2022/01/01');
const date2 = new Date('2022/01/02');
const year1 = date1.getFullYear();
const month1 = date1.getMonth();
const day1 = date1.getDate();
const year2 = date2.getFullYear();
const month2 = date2.getMonth();
const day2 = date2.getDate();
if (year1 === year2 && month1 === month2 && day1 === day2) {
console.log('date1 等于 date2');
} else if (date1 > date2) {
console.log('date1 晚于 date2');
} else {
console.log('date1 早于 date2');
}
在上面的代码中,我们使用了 getFullYear()
、getMonth()
和 getDate()
方法来分别获取日期对象的年、月、日属性。最后,通过简单的条件判断,我们可以得到两个日期对象的比较结果。