仅比较时刻对象中的时间部分

时间:2018-04-24 09:10:34

标签: javascript momentjs date-comparison

我只想比较片刻物体中的时间部分。我已经包含了一个目前不能按预期工作的Snippet。过滤功能无法正常工作。我想过滤掉在07:00之前设置的开始时间或在19:00之后设置的结束时间的所有日期。我也得到一个不赞成的警告,我无法弄清楚原因。感谢所有帮助



var arrayOfWorkDates = [{
  start: "2018-05-02T07:00:00Z",
  end: "2018-05-02T09:00:00Z"
}, {
  start: "2018-05-02T019:00:00Z",
  end: "2018-05-02T21:00:00Z"
}, {
  start: "2018-05-02T010:00:00Z",
  end: "2018-05-02T11:00:00Z"
}];

console.log(arrayOfWorkDates);

var StartHour = moment("07:00", "HH:mm");
var EndHour = moment("19:00", "HH:mm");

var filteredWokrHours = arrayOfWorkDates.filter(function(el) {

  return moment(el.start).isBefore(StartHour) || moment(el.end).isAfter(EndHour);
});

if(filteredWokrHours.length > 0){console.log("success: " + filteredWokrHours.length);}else{console.log("fail");}

<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.1/moment.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

像这样解决了。

&#13;
&#13;
var format = "HH:mm:ss";
var hourFormat = "HH:mm";
var maxStartHour = moment("07:00:00", format);
var minEndHour = moment("19:00:00", format);

var arrayOfWorkDates = [

  {
    start: "2018-02-24T14:00:00",
    end: "2018-02-24T15:00:00"
  },
  {
    start: "2018-02-24T05:00:00",
    end: "2018-02-24T06:00:00"
  },
  {
    start: "2018-02-24T20:00:00",
    end: "2018-02-24T21:00:00"
  }
];


var filteredWokrHours = arrayOfWorkDates.filter(function(el) {

  var start = moment(el.start).format(hourFormat);
  var end = moment(el.end).format(hourFormat);

  var checkHourStart = moment(start, format);
  var checkHourEnd = moment(end, format);

  return checkHourStart.isBefore(maxStartHour) || checkHourEnd.isAfter(minEndHour);
});

if(filteredWokrHours.length > 0){console.log("success: " + filteredWokrHours.length);}else{console.log("fail");}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
&#13;
&#13;
&#13;