给定开始时间和结束时间,如何在这两个时间之间生成一个时间范围数组。我面临的问题是结束时间延长到第二天。
在每个给定时间添加15分钟的功能。
function addMinutes(time, minutes) {
var date = new Date(new Date('01/01/2017 ' + time).getTime() + minutes * 60000);
var tempTime = ((date.getHours().toString().length == 1) ? '0' + date.getHours() : date.getHours()) + ':' +
((date.getMinutes().toString().length == 1) ? '0' + date.getMinutes() : date.getMinutes());
return tempTime;
}
循环开始和结束时间以生成间隔为15分钟的时间范围数组
start = '12:00';
end = '02:45'; //extended to the next day
var range = [start];
while(start <= end) {
start = controller.addMinutes(start, interval);
console.debug(start);
range.push(start);
}
console.debug(range);//this should contain all time range
上面的代码,保持循环并且不会仅生成时间范围 如果开始和结束时间延长到第二天。
我该如何解决?
答案 0 :(得分:1)
你不能用字符串来做。您必须使用Date对象。
// define the start and end date and time
var start = new Date(2018, 1, 11, 23, 00, 00);
var end = new Date(2018, 1, 12, 2, 45, 00);
var range = [];
while(start <= end) {
var Hours = start.getHours();
var Minutes = start.getMinutes();
Minutes = Minutes == 0 ? "00" : Minutes;
range.push(Hours + ":" + Minutes);
start = new Date(start.getTime() + 15 * 60000);
}
console.log(range);
&#13;