简体   繁体   中英

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

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

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. There is not an isBefore function on a plain JS string, so you will get an error.

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.

Also, when checking to see if the two values are on the same date, I would use startOf('day') rather than formatting a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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