How to check if current time falls within a specific range considering also minutes

前端 未结 4 595
囚心锁ツ
囚心锁ツ 2021-01-19 14:20

I am doing a Website for Restaurants Home Delivery ,depending on Restaurant\'s Home Delivery Timings i need to enable / disable Order Now Button

I have got startTim

4条回答
  •  囚心锁ツ
    2021-01-19 15:10

    Something like this should work

    var startTime = '6:30 PM';
    var endTime   = '8:30 AM';
    var now       = new Date();
    
    var startDate = dateObj(startTime); // get date objects
    var endDate   = dateObj(endTime);
    
    if (startDate > endDate) { // check if start comes before end
        var temp  = startDate; // if so, assume it's across midnight
        startDate = endDate;   // and swap the dates
        endDate   = temp;
    }
    
    var open = now < endDate && now > startDate ? 'open' : 'closed'; // compare
    console.log('Restaurant is ' + open);
    
    function dateObj(d) { // date parser ...
        var parts = d.split(/:|\s/),
            date  = new Date();
        if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
        date.setHours(+parts.shift());
        date.setMinutes(+parts.shift());
        return date;
    }
    .as-console-wrapper {top : 0!important}

    It splits those times and adds 12 to PM times, then creates date objects that can easily be compared.

提交回复
热议问题