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)
JavaScript
x
3
1
let startTime = "22:00:00";
2
let endTime = "02:00:00";
3
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)
JavaScript
1
3
1
let startTime = "22:00:00";
2
let endTime = "23:53:00";
3
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.
JavaScript
1
17
17
1
const startTime_1 = "22:00:00";
2
const endTime_1 = "02:00:00";
3
4
const momentStart_1 = moment(startTime_1, 'hh:mm:ss');
5
const momentEnd_1 = moment(endTime_1, 'hh:mm:ss');
6
7
const hasSpanned_1 = momentStart_1.isAfter(momentEnd_1);
8
console.log(`${startTime_1} -> ${endTime_1} ==> Spanned: ${hasSpanned_1}`); // true.
9
10
const startTime_2 = "22:00:00";
11
const endTime_2 = "23:53:00";
12
13
const momentStart_2 = moment(startTime_2, 'hh:mm:ss');
14
const momentEnd_2 = moment(endTime_2, 'hh:mm:ss');
15
16
const hasSpanned_2 = momentStart_2.isAfter(momentEnd_2);
17
console.log(`${startTime_2} -> ${endTime_2} ==> Spanned: ${hasSpanned_2}`); // true.
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>