edward edward - 1 month ago 6
Javascript Question

Trying to check the current time falls inside a range of start/end time using momentJS (UTC)

Trying to check if the current time is between start and end time.

Everything is in UTC, any ideas?

Works



shiftCurrentTime = moment.utc().format('hh:mm');
console.log(shiftCurrentTime);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>





Doesn't work



shiftStartTime = moment.utc('20:00').format('hh:mm'),
shiftEndTime = moment.utc('05:00').format('hh:mm'),
shiftCurrentTime = moment.utc().format('hh:mm');

console.log(shiftCurrentTime.isBetween(shiftStartTime, shiftEndTime));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>




Answer

You are confusing between moment objects and their string representation (given by format())

You have to parse your string into moment object specifying format, since HH:mm is not a known ISO 8601 format.

You can call isBetween on the moment object, while calling it on the formatted string gives you error.

Here a complete working example:

var shiftStartTime = moment.utc('20:00', 'HH:mm'),
shiftEndTime = moment.utc('05:00', 'HH:mm'),
shiftCurrentTime = moment.utc();

console.log(shiftCurrentTime.isBetween(shiftStartTime, shiftEndTime));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>

Comments