jQuery:如果当前时间介于从json

时间:2018-08-09 21:24:21

标签: jquery json momentjs

我有以下json输出:

    [{"shift":"1","start":"08:00","end":"20:00"},
     {"shift":"2","start":"09:00","end":"21:00"},
     {"shift":"3","start":"10:00","end":"22:00"},
     {"shift":"4","start":"11:00","end":"23:00"},
     {"shift":"5","start":"12:00","end":"00:00"},
     {"shift":"6","start":"13:00","end":"01:00"},
     {"shift":"7","start":"14:00","end":"02:00"} .... ]

并希望在当前时间落在两个时间之间时打印班次号,即: 如果当前时间是10:30,那么我会得到:

班次1 班次2 移位3

$.getJSON( "http://server/api/shifts", function( data )   {   
   $.each(data, function(index, item)    {
        var shiftStart = item.start,
        shiftEnd = item.end,
        now = moment().format("HH:mm") ; 
        if (now > shiftStart && now < shiftEnd) {
        var x = document.getElementById("shift_id");
        var option = document.createElement("option");
        option.text = item.shift;
        x.add(option);
        }    
    });  
 });

在选择框中我什么也没得到

1 个答案:

答案 0 :(得分:0)

问题在于轮班在第二天结束。

解决方案是比较时刻对象,我们可以在该对象上设置时间添加1天。

var data = [
  {"shift":"1","start":"08:00","end":"20:00"},
  {"shift":"2","start":"09:00","end":"21:00"},
  {"shift":"3","start":"10:00","end":"22:00"},
  {"shift":"4","start":"11:00","end":"23:00"},
  {"shift":"5","start":"12:00","end":"00:00"},
  {"shift":"6","start":"13:00","end":"01:00"},
  {"shift":"7","start":"14:00","end":"02:00"}
]

// getJSON commented out since it's a "simulated" request.
//$.getJSON( "http://server/api/shifts", function( data )   {   
  $.each(data, function(index, item){
    var start = item.start.split(":"),
        shiftStart = moment().hour(start[0]).minute(start[1]),
        end = item.end.split(":"),
        shiftEnd = moment().hour(end[0]).minute(end[1]),
        now = moment();

    // Forcing now to 13:30, just for this demo...
    now = now.hour(13).minute(30);

    if(shiftEnd<shiftStart){
      console.log("The shift "+item.shift+" ends on the next day.");
      shiftEnd.add(1,"d");
    }

    if (now > shiftStart && now < shiftEnd) {
      var x = document.getElementById("shift_id");
      var option = document.createElement("option");
      option.text = item.shift;
      x.add(option);
      console.log("Adding shift "+item.shift);
    }    
  });  
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

<select id="shift_id"></select>

相关问题