0

I use Vue.js and Moment.js library to work with time and I need to compare the hours and minutes, not date. For example, I need to compare '12:00' and '13:45' and I use .isBefore function (docs).

I tried a bunch of functions and they work with dates, but not time exactly (I tried lots of examples, so this is last of them)

I use moment as a prototype, so $ is ok

let time = this.$moment('10:00-11:30'.split('-')[0], 'HH:mm').format('HH:mm');
let time2 = this.$moment(new Date(), 'HH:mm').format('HH:mm');
console.log({time, time2});
console.log(this.$moment(time.format('hh:mm').isBefore(this.$moment('12:00'), 'hh:mm'))
console.log(this.$moment(time, 'hh:mm').format('hh:mm').isBefore(this.$moment(time2).format('hh:mm'), 'hh:mm'))
console.log(this.$moment(this.$moment('10:00', 'HH:mm').format('HH:mm')).isBefore(this.$moment('12:00'),'HH:mm'));
console.log(this.$moment(this.$moment('10:00', 'HH:mm').format('HH:mm')).isBefore(this.$moment(time2).format('HH:mm'),'HH:mm'));

Some of them return false, but should return true, and some of them return error .isBefore is not a function. I also find this, this and this, but it works only with exactly dates, but not only hours and minutes

Can someone help me to figure out what I did wrong?

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
Yaroslav Saenko
  • 517
  • 2
  • 7
  • 21

1 Answers1

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>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112