Skip to content

Checking if time falls between two times using moment not working correctly

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:

var dropoff_date = new Date(document.getElementById("car-rental-dropoff-date").value);
var dropoff_time_string = document.getElementById("car-rental-dropoff-time").value;
var format = 'h:mm A';
var dropoff_time = moment(dropoff_time_string,format),
ahStart = moment('4:29 PM', format),
ahEnd = moment('8:59 AM', format);

if ((moment(dropoff_time).isBetween(ahStart, ahEnd)) {
    alert ("it works!");
}

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:

var dropoff_time_string = document.getElementById("car-rental-dropoff-time").value;
var format = 'h:mm A';
var dropoff_time = moment(dropoff_time_string,format),

closingToday = moment('4:30 PM', format),
closingYesterday = moment('4:30 PM', format).subtract(1, 'day'),
openingToday = moment('9:00 AM', format),
openingTomorrow = moment('9:00 AM', format).add(1, 'day');

if (((moment(dropoff_time).isBetween(closingYesterday , openingToday)) || (moment(dropoff_time).isBetween(closingToday , openingTomorrow))) {
    //bill = (bill+20000);
    alert ("IT WORKS!" );
}

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:

var format = "MM-DD-YY hh:mm A";
var dropoff_time = moment("01-01-01 8:21 pm", format);
var ahStart = moment('01-01-01 4:30 pm', format);
var ahEnd = moment('01-02-01 8:30 am', format);

if (dropoff_time.isBetween(ahStart, ahEnd)) {
    console.log("it works!");
}