本文介绍了在JavaScript中每X分钟生成一次时间数组(作为字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在整个24小时内每X分钟创建一次时间数组(字符串,不是Date
对象).例如,对于5分钟的时间间隔,数组将为:
I'm trying to create an array of times (strings, not Date
objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the array would be:
['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']
我快速而又肮脏的解决方案是使用3个嵌套的for
循环:
My quick and dirty solution was to use 3 nested for
loops:
var times = []
, periods = ['AM', 'PM']
, hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
, prop = null
, hour = null
, min = null;
for (prop in periods) {
for (hour in hours) {
for (min = 0; min < 60; min += 5) {
times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);
}
}
}
这将输出所需的结果,但我想知道是否有更优雅的解决方案.有没有办法做到这一点:
This outputs the desired result but I'm wondering if there's a more elegant solution. Is there a way to do this that's:
- 更具可读性
- 时间复杂度低
推荐答案
如果仅以分钟为单位设置间隔[0-60],则不创建日期对象并在单循环中评估以下解决方案:
If the interval is only to be set in minutes[0-60], then evaluate the below solution w/o creating the date object and in single loop:
var x = 5; //minutes interval
var times = []; // time array
var tt = 0; // start time
var ap = ['AM', 'PM']; // AM-PM
//loop to increment the time and push results in array
for (var i=0;tt<24*60; i++) {
var hh = Math.floor(tt/60); // getting hours of day in 0-24 format
var mm = (tt%60); // getting minutes of the hour in 0-55 format
times[i] = ("0" + (hh % 12)).slice(-2) + ':' + ("0" + mm).slice(-2) + ap[Math.floor(hh/12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt = tt + x;
}
console.log(times);
这篇关于在JavaScript中每X分钟生成一次时间数组(作为字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!