I am trying to check if a time occurs between two times 4:29 PM and 8:59AM using moment.js, however it doesn’t work, here is my code:
JavaScript
x
11
11
1
var dropoff_date = new Date(document.getElementById("car-rental-dropoff-date").value);
2
var dropoff_time_string = document.getElementById("car-rental-dropoff-time").value;
3
var format = 'h:mm A';
4
var dropoff_time = moment(dropoff_time_string,format),
5
ahStart = moment('4:29 PM', format),
6
ahEnd = moment('8:59 AM', format);
7
8
if ((moment(dropoff_time).isBetween(ahStart, ahEnd)) {
9
alert ("it works!");
10
}
11
However it does work if I change 8:59AM to 9:00 PM, it just doesn’t work if I go into the AM, can anyone help me fix this?
EDIT 3: I just got it working, but this code seems a little much, I would appreciate it if anyone has a better way of doing this:
JavaScript
1
14
14
1
var dropoff_time_string = document.getElementById("car-rental-dropoff-time").value;
2
var format = 'h:mm A';
3
var dropoff_time = moment(dropoff_time_string,format),
4
5
closingToday = moment('4:30 PM', format),
6
closingYesterday = moment('4:30 PM', format).subtract(1, 'day'),
7
openingToday = moment('9:00 AM', format),
8
openingTomorrow = moment('9:00 AM', format).add(1, 'day');
9
10
if (((moment(dropoff_time).isBetween(closingYesterday , openingToday)) || (moment(dropoff_time).isBetween(closingToday , openingTomorrow))) {
11
//bill = (bill+20000);
12
alert ("IT WORKS!" );
13
}
14
Advertisement
Answer
The moment parser is picky I guess. This format works, plus you were missing some var
declarations on the time variables and missing some semicolons at the end of lines:
JavaScript
1
9
1
var format = "MM-DD-YY hh:mm A";
2
var dropoff_time = moment("01-01-01 8:21 pm", format);
3
var ahStart = moment('01-01-01 4:30 pm', format);
4
var ahEnd = moment('01-02-01 8:30 am', format);
5
6
if (dropoff_time.isBetween(ahStart, ahEnd)) {
7
console.log("it works!");
8
}
9