如何比较两个不同的时刻?

How to compare two different time in moment?

我在这里查看了很多关于比较时刻日期的问题,但 none 会解决我的问题。我正在比较两个日期。代码如下。 params.startparams.end 中有日期字符串,例如 '8:15 PM'Slots[0].slot.forEach 只是因为我正在遍历 db.

中的数组
if (params.start && params.end) {
  slots[0].slots.forEach((slot) => {
    //slot.start and slot.end are coming from database
    let dbStart = moment(slot.start, "hh:mm A").format("hh:mm A"); //8:15 PM
    let dbEnd = moment(slot.end, "hh:mm A").format("hh:mm A"); //9:00 PM

    //start and end have the data the user has passed
    let start = moment(params.start).format("LT"); //8:30 PM
    let end = moment(params.end).format("LT"); //8:50 PM

    console.log(start, end, dbStart, dbEnd);
    //8:30 PM 8:50 PM 8:15 PM 9:00 PM

    console.log(typeof start, typeof end, typeof dbStart, typeof dbEnd);
    //string string string string

    let status = slot.status;

    if (start >= dbStart && end <= dbEnd)
      //The above condition is not working as expected. 
      //It is not comparing the values 8:30 >= 8:15 and 8:50<= 9:00 should return true 
      //but it is returning false for some reason. 
      temp.push({
        dbStart,
        dbEnd,
        status
      });
  });
}

我是不是比较错了?任何帮助将不胜感激。

通过调用方法 .format() 将返回一个字符串。在您的代码中,您将这些字符串保存为参数:dbStartdbEnd 等。然后您将比较它们,因此 a.t.m。您正在比较字符串,而您应该比较 Moment.js 对象。所以只需删除 .format() 调用,将代码更改为:

if (params.start && params.end) {
  slots[0].slots.forEach((slot) => {
    //slot.start and slot.end are coming from database
    let dbStart = moment(slot.start, "hh:mm A");
    let dbEnd = moment(slot.end, "hh:mm A");

    //start and end have the data the user has passed
    let start = moment(params.start);
    let end = moment(params.end);

    let status = slot.status;

    if (start >= dbStart && end <= dbEnd)
      //The above condition is not working as expected. 
      //It is not comparing the values 8:30 >= 8:15 and 8:50<= 9:00 should return true 
      //but it is returning false for some reason. 
      temp.push({
        dbStart,
        dbEnd,
        status
      });
  });
}