javascript 中的字符串日期比较

String dates comparison in javascript

所以,我有两个变量和一个函数:

 function addDays(date, days) {
    var result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
  }
  
 const dateToCompare=moment.utc(endDate).format('DD-MM-YYYY')
 const maximum=moment.utc(addDays(new Date(),14)).format('DD-MM-YYYY')

但是,我不知道如何比较它们,因为它们现在被格式化为字符串,但同时 new Date(dateToCompare) 不起作用。

有人可以给我提示吗?

如果你想做的是去掉时间,只是比较日期,不要进行字符串转换;在进行日期比较之前,只需将 Date 对象的小时、分钟和秒设置为零。

let foo = new Date();
console.log(foo);// date includes time
foo.setHours(0); foo.setMinutes(0); foo.setSeconds(0);
console.log(foo) // date set to midnight (in your timezone)

为什么在使用 moment.js 时使用内置方法来添加天数?考虑:

let maximum = moment.utc().add('day',14).format('DD-MM-YYYY')

要将日期设置为一天的开始,请使用 moment.js startOf 方法:

let maximum = moment.utc().add('day',14).startOf('day')
let dateToCompare = moment.utc(endDate).startOf('day')

如果格式为 YYYY-MM-DD,您可以将日期作为字符串进行比较,或者将它们保留为时刻对象并使用 isSame, isAfter, isSameOrBefore 等进行比较

当解析字符串时:

const dateToCompare=moment.utc(endDate)

除非 endDate 是 Date 或 moment 对象,否则您应该始终传递要解析的格式。 new Date(dateToCompare) 不起作用,因为 Why does Date.parse give incorrect results?