Search code examples
javascriptmomentjstempus-dominus-datetimepicker

Issue Comparing Moments in JavaScript


I've got the following code that checks to see whether the start date is >= to the end date. Almost every time I compare the two dates when they are identical, the difference between the dates is something less than 0.

Here is my code:

var end = $('#job_end').datetimepicker('date');
var start = $('#job_start').datetimepicker('date');

console.log(start);
console.log(end);
console.log(start.diff(end));
console.log(start.isSameOrAfter(end));

Here is the output from this code:

Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Wed Jul 25 2018 14:15:00 GMT-0500 (Central Daylight Time), …}
Moment {_isAMomentObject: true, _isUTC: false, _pf: {…}, _locale: Locale, _d: Wed Jul 25 2018 14:15:00 GMT-0500 (Central Daylight Time), …}
-6
false

Is there something that I am doing wrong?


Solution

  • From reading your code it looks like you have a difference of something like six milliseconds. Since you are getting the end date first and then the start date, that is probably the execution time of those two lines of code. If you are simply looking to compare the date and not the time as well, check and make sure you are only getting the date and not the time.

    Look at using moment().startOf('day') which will zero the time and you can compare only the day.