Marian Montagnino
Marian Montagnino

Reputation: 135

Moment js: unexpected behavior using inBetween method

I'd expect that the current time Saturday, October 13, 2018 9:32 PM would be between Saturday, October 13, 2018 9:00 PM and Sunday, October 14, 2018 12:00 AM but moment js says it's not. Any idea how this is possible?

var currentTime = moment();
console.log("moment(): ", moment().format('LLLL'))
console.log("currentTime: ", currentTime.format('LLLL'))
var start_time = moment(currentTime.format('YYYY-MM-DD') + ' ' + '21:00:00');
var currentTimePlusDay = currentTime.add(1,'days');
var extra = currentTimePlusDay.format('YYYY-MM-DD') + ' ';
var end_time = moment(extra + '00:00:00');

console.log("start_time: ", start_time.format('LLLL'))
console.log("end_time: ", end_time.format('LLLL'))
var midnight;
console.log("moment(currentTime).isBetween(start_time, end_time): ", moment(currentTime).isBetween(start_time, end_time))

Using timezone: America/New_York, output:

moment():  Saturday, October 13, 2018 9:32 PM
currentTime:  Saturday, October 13, 2018 9:32 PM
start_time:  Saturday, October 13, 2018 9:00 PM
end_time:  Sunday, October 14, 2018 12:00 AM
moment(currentTime).isBetween(start_time, end_time):  false

Upvotes: 0

Views: 50

Answers (1)

Akrion
Akrion

Reputation: 18515

I changed (cloned) currentTime in your assignment to currentTimePlusDay as:

var currentTime = moment();
console.log("moment(): ", moment().format('LLLL'))
console.log("currentTime: ", currentTime.format('LLLL'))
var start_time = moment(currentTime.format('YYYY-MM-DD'));
var currentTimePlusDay = currentTime.clone().add(1,'days');  // <--- THIS
var extra = currentTimePlusDay.format('YYYY-MM-DD') + ' ';
var end_time = moment(extra + '00:00:00');

console.log("start_time: ", start_time.format('LLLL'))
console.log("end_time: ", end_time.format('LLLL'))
console.log("currenttime: ", currentTime.format('LLLL'))
console.log("moment(currentTime).isBetween(start_time, end_time): ", moment(currentTime).isBetween(start_time, end_time))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

If you do not do that that day added ends up mutating the currentTime which screws with your in between range.

Also changed the start time to not start from 21:00:00 to make sure it works. But the clone() change was the difference. See if this helps.

Upvotes: 2

Related Questions