Reputation: 11
Thanks in advance...I'm new to using Moment and in the code below not sure why the check to isBetween is true. I see that the date portion is between the given dates but the time isn't. Not sure if I'm using the command correctly.
var beginningTime = moment('2016-11-25 3:45 am', 'YYYY-MM-DD h:mma');
var endTime1 = moment('2016-11-22 9:00 am', 'YYYY-MM-DD h:mma');
var endTime2 = moment('2016-11-30 1:00 pm', 'YYYY-MM-DD h:mma');
console.log("Beg Time = "+beginningTime.toString());
console.log("End Time1 = " +endTime1.toString());
console.log("End Time2 = "+endTime2.toString());
console.log(beginningTime.isBetween(endTime1,endTime2));
VM5431:4 Beg Time = Fri Nov 25 2016 03:45:00 GMT-0500
VM5431:5 End Time1 = Tue Nov 22 2016 09:00:00 GMT-0500
VM5431:6 End Time2 = Wed Nov 30 2016 13:00:00 GMT-0500
VM5431:7 true
Upvotes: 1
Views: 9225
Reputation: 31482
As the docs says, isBetween
:
Check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc). The match is exclusive
The comparison takes in accout the full object (both date and time info) so the result for your example is correct (2016-11-25 3:45 am
is between 2016-11-22 9:00 am
and 2016-11-30 1:00 pm
).
If you what to compare only time, your moment objects should have the same date values (day, month, year). One way to achieve that, starting from your moment objects (beginningTime
, endTime1
, endTime2
), is using moment({unit: value, ...})
constructor. Setting only hour
and minute
properties, it will create a moment object for the current day.
hour()
and minute()
get hours and minutes for the given moment.
Here a working example:
var beginningTime = moment('2016-11-25 3:45 am', 'YYYY-MM-DD h:mm a');
var endTime1 = moment('2016-11-22 9:00 am', 'YYYY-MM-DD h:mm a');
var endTime2 = moment('2016-11-30 1:00 pm', 'YYYY-MM-DD h:mm a');
console.log("Beg Time = "+beginningTime.toString());
console.log("End Time1 = " +endTime1.toString());
console.log("End Time2 = "+endTime2.toString());
console.log(beginningTime.isBetween(endTime1,endTime2));
// Create a moment object considering only hour and minute
function getMomentTime(m){
return moment({hour: m.hour(), minute: m.minute()});
};
var t1 = getMomentTime(endTime1);
var t2 = getMomentTime(endTime2);
var begin = getMomentTime(beginningTime);
console.log("Beg Time = "+begin.toString());
console.log("End Time1 = " +t1.toString());
console.log("End Time2 = "+t2.toString());
console.log(begin.isBetween(t1, t2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
Upvotes: 8