Reputation: 91
i 3 given times, i want to check if myTime is in between start time and end time.
import moment from "moment";
const startTime= moment("18:45", "hh:mm").format("hh:mm a");
const endTime = moment("09:30", "hh:mm").format("hh:mm a");
const myTime= moment("19:00", "hh:mm").format("hh:mm a");
console.log(startTime, endTime , myTime);
// starttime 18:45
// endTime 09:30
console.log(moment(myTime).isBetween(startTime, endTime ))
Upvotes: -1
Views: 863
Reputation: 1075517
It's because the time isn't between the start and end times. All of your times are being treated as being on the same day, since you're just parsing time values without dates. 19:00
is not between 09:30
and 18:45
. It would be between 18:45
on one day and 09:30
the next, but that's not what you're testing. (Even though the documentation says the "smaller" value should be in the first argument, it still looks at the actual values, it doesn't guess that you meant one of them to be later.) If you want to test that, add a day to endTime
. I also recommend not formatting prematurely; only format for output.
const startTime = moment("18:45", "hh:mm");
const endTime = moment("09:30", "hh:mm");
if (endTime < startTime) {
endTime.add(1, "day");
}
const myTime = moment("19:00", "hh:mm");
console.log(`startTime = ${startTime.format("yyyy-MM-DD hh:mm a")}`);
console.log(`endTime = ${endTime.format("yyyy-MM-DD hh:mm a")}`);
console.log(`myTime = ${myTime.format("yyyy-MM-DD hh:mm a")}`);
console.log(myTime.isBetween(startTime, endTime));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Upvotes: 1