Given the following two times without dates and using moment, how can I best check the following two scenarios based on 24 hours times:
1)
let startTime = "22:00:00"; let endTime = "02:00:00";
Using the startTime
I need to set some flag (boolean) indicating that the endTime
has spanned over to the next day and not within the same 24 hour period of the startTime
?
2)
let startTime = "22:00:00"; let endTime = "23:53:00";
the same as item (1) but this time setting a flag indicating that the startTime
and endTime
are within the same 24 hour period
Advertisement
Answer
Here’s a snippet. Took the liberty to replace let
by const
, as there are no expected modifications to the variables.
const startTime_1 = "22:00:00"; const endTime_1 = "02:00:00"; const momentStart_1 = moment(startTime_1, 'hh:mm:ss'); const momentEnd_1 = moment(endTime_1, 'hh:mm:ss'); const hasSpanned_1 = momentStart_1.isAfter(momentEnd_1); console.log(`${startTime_1} -> ${endTime_1} ==> Spanned: ${hasSpanned_1}`); // true. const startTime_2 = "22:00:00"; const endTime_2 = "23:53:00"; const momentStart_2 = moment(startTime_2, 'hh:mm:ss'); const momentEnd_2 = moment(endTime_2, 'hh:mm:ss'); const hasSpanned_2 = momentStart_2.isAfter(momentEnd_2); console.log(`${startTime_2} -> ${endTime_2} ==> Spanned: ${hasSpanned_2}`); // true.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>