Lorenzo Varano
Lorenzo Varano

Reputation: 411

isBefore function in momentjs is not working

I try to check if a certain time in h:mm is before another time with same format. However, the console shows me either an error saying isBefore is not a function or it always print false. I use this code in Ionic 3/Angular.

If I code as follows, the console prints false. I tried different arguments instead of hour.

  var start_time = moment('20:00', 'h:mm').format('LT');
  var last_time = moment('21:59', 'h:mm').format('LT');
  var check_last = moment(start_time).isBefore(last_time, 'hour');
  console.log(check_last);

If I code as follows. As found on the link below. The console give me the error is

  var start_time = moment('20:00', 'h:mm').format('LT');
  var last_time = moment('21:59', 'h:mm').format('LT');
  var check_last = start_time.isBefore(last_time, 'hour');
  console.log(check_last);

Moment.js isBefore function not working as expected

On the official website of momentjs I didn't figure out how to compare two times. Can you please give me support?

Upvotes: 2

Views: 3090

Answers (2)

joy08
joy08

Reputation: 9652

Moment's format() returns a string so you can't use isBefore on something like time.format('hh:mm'), that's the reason you are getting isBefore is not a function.

Also as per the docs itself , moment().isBefore() has undefined behavior and should not be used! If the code runs fast the initial created moment would be the same as the one created in isBefore to perform the check, so the result would be false

Try it without formatting to get the desired output

var start_time = moment("20:00", "h:mm");
var last_time = moment("21:59", "h:mm");
var check_last = moment(start_time).isBefore(last_time, "hour");
console.log(check_last);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Upvotes: 2

jjgg
jjgg

Reputation: 670

So the reason isBefore() is not working as expected is the formatting. Formatting the time returns a string which may cause errors when comparing.

If you save the times as moment objects, then moment can compare them accurately. You can format after comparing. Here is an example:

var start_time = moment('20:00', 'h:mm');
var last_time = moment('21:59', 'h:mm');
var check_last = moment(start_time).isBefore(last_time, 'hour');
console.log(check_last);
// format at end
// return [
//   start_time.format('LT'),
//   last_time.format('LT'),
// ];
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment.min.js"></script>

Upvotes: 0

Related Questions