[Vuejs]-Moment.js time comparing

0👍

There are a couple of issue in your code sample, first of all format() returns a string so you can’t use isBefore on something like time.format('hh:mm'), that’s why you are getting isBefore is not a function

Moreover a moment object always represent a given moment in time (date + time) even if you are creating it by providing only time values. As the Defaults section of the docs states:

You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.

I suggest to use format() (without arguments) to inspect your moment objects’ value to better understand why you are getting unexpected results.

Here un updated version of your code sample (without vue.js), to show how you can use isBefore:

let time = moment('10:00-11:30'.split('-')[0], 'HH:mm');
let time2 = moment();
console.log( time.format(), time2.format() );
console.log( time.isBefore(moment('12:00', 'hh:mm')) );
console.log( time.isBefore(time2) );
console.log( moment('10:00', 'HH:mm').isBefore(moment('12:00','HH:mm')) );
console.log( moment('10:00', 'HH:mm').isBefore(time2) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Leave a comment