在javascript中重叠小时

时间:2016-11-01 00:02:20

标签: javascript json overlapping

我正在处理重叠小时的问题。故事是这样的 - 我有一个带有条形图和系统的网站,应该向用户显示现在打开哪个条形图。当我使用检查当前时间的方法时,我不能因为时间也到第二天也很困难。例如。一家酒吧在上午9点营业,第二天凌晨2点营业。我如何解决这个问题,我的代码如下 - 我在JSON中获得了时间。

    var current_time = new Date().toLocaleTimeString('en-US', { hour12: false, hour: "numeric", minute: "numeric"});

    var d = new Date();
    var weekday = new Array(7);
    weekday[0]=  "sundayStart";
    weekday[1] = "mondayStart";
    weekday[2] = "tuesdayStart";
    weekday[3] = "wednesdayStart";
    weekday[4] = "thursdayStart";
    weekday[5] = "fridayStart";
    weekday[6] = "saturdayStart";
    var n = weekday[d.getDay()];

    var weekday1 = new Array(7);
    weekday1[0]=  "sundayEnd";
    weekday1[1] = "mondayEnd";
    weekday1[2] = "tuesdayEnd";
    weekday1[3] = "wednesdayEnd";
    weekday1[4] = "thursdayEnd";
    weekday1[5] = "fridayEnd";
    weekday1[6] = "saturdayEnd";
    var m = weekday1[d.getDay()];

因此,此代码首先检查现在是哪一天,然后在START和END数组值中查找值。由于第二天的重叠值,我不能在方法之间使用。非常感谢。

2 个答案:

答案 0 :(得分:0)

一种方法是每天有多个范围,因此它们不会跨越午夜。因此,不要说它在星期一上午9点​​到凌晨2点开放,而周二从上午10点到凌晨3点开放,请执行以下操作:

Monday: 09:00 - 23:59
Tuesday: 00:00 - 02:00, 10:00-23:59
Wednesday: 00:00 - 03:00

因此,一周中的每一天都会有一组{open: xxx, close: xxx}个对象。循环遍历当天的所有对象,如果当前时间在任何范围内,则返回true

如果您的输入JSON不是这样,您可以通过处理输入来创建它。每当关闭时间小于开放时间时,将其分成两个范围。第一个范围是从开放时间到同一天的23:59,第二个范围是从00:00到第二天的关闭时间。

答案 1 :(得分:0)

您可以将开启和关闭时间表示为开始和结束时间,因此如果bar1在上午9点打开并在第二天凌晨2点关闭,第2栏在下午3点开放并在第二天早上6:30关闭,那么& #39; d:

  1. bar1:09:00,17:00
  2. bar2:15:00,15:30
  3. 
    
    var times = {bar1: ['09:00', '17:00'], bar2: ['15:00', '15:30']};
    
    function showBarTimes(data) {
      Object.keys(data).forEach(function(bar) {
        var open = new Date();
        var openTime = times[bar][0].split(':');
        var duration = times[bar][1].split(':');
        open.setHours(openTime[0], openTime[1], 0,0);
        var close = new Date(+open);
        close.setHours(close.getHours() + +duration[0], close.getMinutes() + +duration[1]);
        var now = new Date();
        var currentlyOpen = now >= open && now <= close;
    
        console.log(bar + ' opens at ' +
                    open.toLocaleString() + ' and closes at ' +
                    close.toLocaleString() + ' and is currently ' + 
                    (currentlyOpen? 'OPEN':'CLOSED'));
      });
    }
    showBarTimes(times);
    &#13;
    &#13;
    &#13;