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 arr
This is an iteration of Faizan Saiyed's answer.
const startHour = moment().format('k');
const endHour = 22
const arr = () => {
return Array.from({
length: endHour - startHour
}, (v, index) => {
return [0,15,30,45].map((interval) => {
return moment({
hour: index,
minute: interval
})
.add(startHour, 'hours')
.format('h:mm A')
})
}).flat()
}
You could use a single for
loop, while
loop , Array.prototype.map()
, Array.prototype.concat()
, String.prototype.replace()
var n = 0,
min = 5,
periods = [" AM", " PM"],
times = [],
hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
for (var i = 0; i < hours.length; i++) {
times.push(hours[i] + ":" + n + n + periods[0]);
while (n < 60 - min) {
times.push(hours[i] + ":" + ((n += 5) < 10 ? "O" + n : n) + periods[0])
}
n = 0;
}
times = times.concat(times.slice(0).map(function(time) {
return time.replace(periods[0], periods[1])
}));
console.log(times)
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 minutes slottime
, but other intervals can be accomplished with the multiplier, again in my case 60000
making minutes added to valueOf()
.
function slotSelect(blockstart, blockend, slottime) {
var markup = "";
var secs = parseInt(slottime * 60000); // steps
var a = parseInt( moment(blockstart).valueOf() ); // start
var b = parseInt( moment(blockend).valueOf() );
var times = _.range(a, b, secs);
_.find( times, function( item ) {
var appttime = moment(item).format('h:mm a');
var apptunix = moment(item).format();
markup += '<option value="'+apptunix+'"> ' + appttime + ' </option>'+"\n";
});
return markup;
}