UnKnown UnKnown - 1 month ago 10
Javascript Question

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

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 startTime and End Time in 12 Hour format .

This is the code

var startTime = '8:30 AM' ;
var endTime = '6:30 PM' ;


var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';

if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"),hours24>11?"pm" :"am"].join(" ");
}
return formatted;
}
})();


var currentTime = formatTime(new Date());


I need to check if the current time is in between startTime and EndTime or not

If its only Hours ,i could have extracted the first character before colon from startTime ,endTime and currentTime and done a comparision like this

if(currentTime >= startTime && currentTime <= endTime)
{
alert('Restaurant Open');
}
else
{
alert('Restaurant Closed');
}


But i need to take the minutes also in consideration ,so could you please let me how to do this comparsion if minutes were takein in consideration ??

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

Answer

Something like this should work

var startTime = '8:30 AM';
var endTime   = '6:30 PM';

var now       = new Date();
var startDate = dateObj(startTime);
var endDate   = dateObj(endTime);

var open = now < endDate && now > startDate ? 'open' : 'closed';
alert('Restaurant is ' + open);

function dateObj(d) {
    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;
}

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

Comments