我想基于两次(military format)做一个JavaScript循环,并且该循环必须返回正常时间。
例如,我有两个变量:
var start_time = 1400; // That mens 14:00 or 2pm
var end_time = 400; // Or 0400 (but it's the same the browser. It's 04:00 or 4 am
我想做一个循环,一个for或while,我希望得到这样的结果:
14:00
15:00
16:00
....
3:00
4:00
我怎么能这样做?谢谢!
答案 0 :(得分:4)
start_time = start_time / 100;
end_time = end_time / 100;
var x = start_time;
while(x >= start_time || x <= end_time) {
if(x > 23) {
x = 0;
}
console.log(x + ":00");
x = x + 1;
}
答案 1 :(得分:0)
总体思路(改进空间):
var start = 1400;
var end = 400;
if (start > end){
end = end + 2400;
}
for (var i = start; i <= end; i += 100)
{
var c = (i % 2400);
var s = c + '';
console.log(s.substring(0, c < 1000 ? 1 : 2) + ':00');
}
使用节点输出:
14:00
15:00
16:00
17:00
18:00
19:00
20:00
21:00
22:00
23:00
0:00
1:00
2:00
3:00
4:00
答案 2 :(得分:0)
在for中循环,将小时递增100。 只需确保在24:00
时将循环变量重置为0:00function loopHours(start_time, end_time) {
function write(hour){
console.log( (hour/100) + ":00" );
}
var hour = start_time;
for (; hour != end_time; hour += 100) {
if (hour >= 2400) {
hour = 0;
}
write(hour);
}
write(end_time);
}
答案 3 :(得分:0)
getFormattedTime = function (fourDigitTime) {
var hours24 = parseInt(fourDigitTime.substring(0, 2), 10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
$('span.mil_time').html(function (i, oldHtml) {
return getFormattedTime(oldHtml);
});
加上一个将变量增加/减少100并在2400到0000重置的循环将满足您的需要。不要忘记这个函数需要id为“mil_time”的jQuery和span标签