JavaScript通过循环数组设置时差
我尝试使用JavaScript中的循环将值存储在Array中。它只适用于我。
Im trying to store values in an Array using a loop in JavaScript. It only works partially for me.
我想在数组中存储时间
会有startTime,结束时间和间隔
There will be startTime, endTime and an interval
例如:
如果想要从9:00到10:00获取时间间隔为15分钟,则应打印
For example: If want to get the time from 9:00 to 10:00 with an interval of 15 minutes, it should print
09:00,09:15,09:30,09:45,10:00
09:00,09:15,09:30,09:45,10:00
但是这是打印
09:00,09:15,09:30,09:45,10:00,10:15,10:30,10:45
09:00,09:15,09:30,09:45,10:00,10:15,10:30,10:45
如果我想在9:30到10:30之间获得时差,我该怎么办?还是9:45和10:45?
Second what should I do if I want to get the time difference between 9:30 and 10:30? or 9:45 and 10:45?
这是我的代码:
HTML
< div id =time>< / div>
JavaScript
JavaScript
var array = new Array();
var timeDiff = 15;
var FirstTime = 9;
var endTime = 10;
for (var xh = FirstTime; xh <= endTime; xh++) {
for (var xm = 0; xm < 60; xm += timeDiff) {
array.push(("0" + xh).slice(-2) + ':' + ("0" + xm).slice(-2));
}
};
$('#time').text(array)
我有创建了一个jsfiddle示例: -
Hi i have created a jsfiddle example:-
var setIntervals = function (start, end, inc) {
start = start.toString().split(':');
end = end.toString().split(':');
inc = parseInt(inc, 10);
var pad = function (n) { return (n < 10) ? '0' + n.toString() : n; },
startHr = parseInt(start[0], 10),
startMin = parseInt(start[1], 10),
endHr = parseInt(end[0], 10),
endMin = parseInt(end[1], 10),
currentHr = startHr,
currentMin = startMin,
previous = currentHr + ':' + pad(currentMin),
current = '',
r = [];
do {
currentMin += inc;
if ((currentMin % 60) === 0 || currentMin > 60) {
currentMin = (currentMin === 60) ? 0 : currentMin - 60;
currentHr += 1;
}
current = currentHr + ':' + pad(currentMin);
r.push(previous + ' - ' + current);
previous = current;
} while (currentHr !== endHr);
return r;
};
点击此处查看示例: - http://jsfiddle.net/w6EQ6/3/
click here to see example:-http://jsfiddle.net/w6EQ6/3/
或者如果你不想打印范围然后看下面给出的链接: -
or if you don't want to print the range then see the below given link:-
解决了这个问题: http://jsfiddle.net/w6EQ6/8/