我根据给定的数据和时间使用时隙,但是我遇到了问题。
我有开始时间 15:00 和结束时间 00:15 ,收到的错误。
function parseTime(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
function convertHours(mins){
var hour = Math.floor(mins/60);
var mins = mins%60;
var converted = pad(hour, 2)+':'+pad(mins, 2);
return converted;
}
function pad(str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
function calculatTimeSlot(startTime, endTime, interval = "15") {
var i, formattedTime;
var timeSlots = new Array();
for (var i = startTime; i <= endTime; i = i + interval) {
formattedTime = convertHours(i);
timeSlots.push(formattedTime);
}
return timeSlots;
}
var startTime = parseTime("15:00"),
endTime = parseTime("00:15"),
interval = 15;
var timesAray = calculatTimeSlot(startTime, endTime, interval);
console.log(timesAray);
在输出中,我有一个空数组,但我想获取:
["15:00", "15:15", "15:30", "15:45"...."00:00", "00:15"]
我该如何解决?
答案 0 :(得分:1)
由于endTime
为“ 00:15”,因此parseTime
函数将返回15,因此循环将永远不会运行。
一个肮脏的解决方法是:
function parseTime(s) {
var c = s.split(':');
if (c[0] === "00") c[0] = "24";
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
然后代码将返回:
["15:00", "15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", "17:00", "17:15", "17:30", "17:45", "18:00", "18:15", "18:30", "18:45", "19:00", "19:15", "19:30", "19:45", "20:00", "20:15", "20:30", "20:45", "21:00", "21:15", "21:30", "21:45", "22:00", "22:15", "22:30", "22:45", "23:00", "23:15", "23:30", "23:45", "24:00", "24:15"]
您还必须重写convertHours
,因为它显示的是24:00
而不是00:00
再次:这不是最好的解决方案,因为@Titus表示最好是增加天数的概念。
答案 1 :(得分:1)
您可以通过使用Date
对象来简化此过程。这是一个示例:
function getDateWithTime(time) {
var date = new Date();
var timeArr = time.split(":").map(v => parseInt(v));
date.setHours(timeArr[0]);
date.setMinutes(timeArr[1]);
return date;
}
function getIntervals(start, end, interval = 15) {
var intervals = [];
while (start <= end) {
var h = start.getHours();
var m = start.getMinutes();
h = String(h).padStart(2, "0");
m = String(m).padStart(2, "0");
intervals.push(`${h}:${m}`);
start.setMinutes(start.getMinutes() + interval);
}
return intervals;
}
var startTime = "15:00";
var endTime = "00:15";
var start = getDateWithTime(startTime);
var end = getDateWithTime(endTime);
if (end < start) { // deal with cases when the intervals span on 2 days
end.setDate(end.getDate() + 1);
}
console.log(getIntervals(start, end, 15));