如何在考虑到分钟的情况下检查当前时间是否在特定范围内 [英] How to check if current time falls within a specific range considering also minutes

查看:86
本文介绍了如何在考虑到分钟的情况下检查当前时间是否在特定范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个用于餐厅送货上门的网站,具体取决于餐厅的送货上门时间,我需要启用/禁用立即订购"按钮

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

我有12小时格式的startTime和End Time.

I have got startTime and End Time in 12 Hour format .

这是代码

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());

我需要检查当前时间是否在startTime和EndTime之间

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

如果只有小时,我可以从startTime,endTime和currentTime中提取冒号之前的第一个字符,并进行类似的比较

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

推荐答案

类似的方法应该起作用

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}

它将这些时间分开,并在PM时间上加12,然后创建可以轻松比较的日期对象.

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

这篇关于如何在考虑到分钟的情况下检查当前时间是否在特定范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆