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']
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:
- more readable
- less time complex
Allocating the resulting array to avoid the overhead of push, parameter validation and locale specifics notwithstanding:
Here's a demo snippet.
The result of this is an array
times
converted into markup that I place in a<select>
object. I found that underscore.js's _.range allows me to step through increments but only as integers. So, I used moment.js to convert to unix time. I needed to iterate over minutesslottime
, but other intervals can be accomplished with the multiplier, again in my case60000
making minutes added tovalueOf()
.You need only one loop, follow this approach
Now keep adding 5 minutes till the
d.getDate()
value changesDemo