简体   繁体   English

我如何使用moment.js比较两个日期

[英]How can i compare two dates using moment.js

I am trying to compare two datetime values becouse what i want to do is to check if the time ha passed 我正在尝试比较两个日期时间值,因为我想做的是检查时间是否过去了

i tryied to use two methods. 我试图使用两种方法。 Using the function isBefore 使用功能isBefore

for (var i = 0; i < vm.conferencesArray.length; i++) {

   if (moment(vm.conferencesArray[i].fecha).format('MMMM Do YYYY') == moment().format('MMMM Do YYYY')) {
    var a = moment('2016-03-12 ' + horaActual[4]).format('MMMM Do YYYY, h:mm:ss a');
    var b = moment('2016-03-12 ' + vm.conferencesArray[i].horaInicio).format('MMMM Do YYYY, h:mm:ss a');

    console.log(a.isBefore(b));
    } else {
      console.log("the event is not today")
      }
}

and using an if, but it didnt worked 并使用一个if,但没有奏效

for (var i = 0; i < vm.conferencesArray.length; i++) {
   if (moment(vm.conferencesArray[i].fecha).format('MMMM Do YYYY') == moment().format('MMMM Do YYYY')) {
      if (moment('2016-03-12 ' + horaActual[4]).format('MMMM Do YYYY, h:mm:ss a') > moment('2016-03-12 ' + vm.conferencesArray[i].horaInicio).format('MMMM Do YYYY, h:mm:ss a')) {
        console.log("next conference");
      } else {
           console.log("previous conference");
        }
   } else {
        console.log("the conference is not today");
     }
}

You are doing... 你在做...

moment(s).format(f)

Thate creates a string with the given output format. Thate用给定的输出格式创建一个字符串 There is not an isBefore function on a plain JS string, so you will get an error. 普通JS字符串上没有isBefore函数,因此您会收到错误消息。

If you were trying to specify the format that your input string was provided in, that is: 如果您尝试指定提供输入字符串的格式,即:

moment(s, f)

Then you will have a moment object, and you can call isBefore and other functions that exist on it. 然后,您将有一个moment对象,并且可以调用isBefore及其上存在的其他函数。

Also, when checking to see if the two values are on the same date, I would use startOf('day') rather than formatting a string. 另外,当检查两个值是否在同一日期时,我将使用startOf('day')而不是格式化字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM