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
My solution with emphasize on readability. It first creates objects that represent correct times and then formats them to strings. JsFiddle https://jsfiddle.net/6qk60hxs/
Manipulating with a date as with integer and using single loop:
This is an iteration of Faizan Saiyed's answer.
The following is massively flexible with the help of Moment.js.
This code uses
There's no error handling, so you can pass in stupid parameters, but it gets the point across. :-D
The
desiredStartTime
parameter takes a time inhh:mm
format.The
period
parameter accepts any of themoment.duration
inputs.Loops are unnecessary in this case.
ES6
Wider browser support