我需要计算两小时JavaScript之间的范围,例如:
var calculeHor = 30; // or 20, or 15, or 10...
var horIni = "8:30";
var horEnd = "13:00";
结果是:
var range = [
{08:30 - 09:00},
{09:00 - 09:30},
{09:30 - 10:00},
{10:00 - 10:30},
{10:30 - 11:00},
{11:00 - 11:30},
{11:30 - 12:00},
{12:00 - 12:30},
{12:30 - 13:00}
];
答案 0 :(得分:1)
应该这样做:
function getRange(start, end, interval) {
function getMinutes(time) {
var a = time.split(':').map(Number);
return a[0] * 60 + a[1];
}
function getTime(m) {
var h = m / 60 | 0;
m %= 60;
return h + ':' + (m < 10 ? '0' + m : m);
}
var r = [],
startM = getMinutes(start),
endM = getMinutes(end);
while (startM + interval <= endM) {
r.push(getTime(startM) + ' - ' + getTime(startM + interval));
startM += interval;
}
return r;
}
document.write('<pre>' + JSON.stringify(getRange('8:30', '13:00', 30), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getRange('9:20', '11:00', 20), 0, 4) + '</pre>');
答案 1 :(得分:1)
试一试:
function time(start, end, interval) {
var s = start.split(':').map(e => +e);
var e = end.split(':').map(e => +e);
var res = [];
var t = [];
while (!(s[0] == e[0] && s[1] > e[1])) {
t.push(s[0] + ':' + (s[1] < 10 ? '0' +s[1] : s[1]));
s[1] += interval;
if (s[1] > 59) {
s[0] += 1;
s[1] %= 60;
}
}
for (var i = 0; i < t.length - 1; i++) {
res.push(t[i] + " - " + t[i + 1]);
}
return res;
}
document.write('<pre>' + JSON.stringify(time('8:30', '13:00', 30), 0, 2) + '</pre>');