user2335485
user2335485

Reputation: 61

Moment JS isBefore return wrong result

I'm having an issue with moment js library. the function isBefore sometimes returns the wrong result. Below code should return true, not false value.

var clockIn = moment('1/5/2018 12:15 AM');
var startBreak = moment('1/5/2018 11:00 AM');

if(startBreak.isBefore(clockIn)){
  console.log('isBefore');
}else{
  console.log('isAfter');
}
<script src="https://momentjs.com/downloads/moment.js"></script>

Please advise.

Upvotes: 2

Views: 1442

Answers (2)

VincenzoC
VincenzoC

Reputation: 31482

You are getting the right result, as 12:15 AM is parsed as 00:15, so startBreak (11:00) is after clockIn (00:15).

Anyway since your input is not in ISO 8601 recognized format, neither in RFC 2822 format, you have to use moment(String, String).

D stands for Day of month, M stands for month number, YYYY stands for 4 digit year, hh stands for 1..12 hour, mm stands for minutes and A stands for AM/PM.

Your current code throws Deprecation Warning and the message in the console points to JS Date Construction guide.

Here a live sample:

var clockIn = moment('1/5/2018 12:15 AM', 'D/M/YYYY hh:mm A');
var startBreak = moment('1/5/2018 11:00 AM', 'D/M/YYYY hh:mm A');

console.log('clockIn: ' + clockIn.format() + ' ' + clockIn.valueOf());
console.log('startBreak: ' + startBreak.format() + ' ' + startBreak.valueOf());

if(startBreak.isBefore(clockIn)){
  console.log('isBefore');
}else{
  console.log('isAfter');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Upvotes: 0

Kartik Prasad
Kartik Prasad

Reputation: 740

12:15 AM is before 11:00 AM perhaps you probably mean to be using 12:15 PM

Upvotes: 4

Related Questions