Generate array of times (as strings) for every X minutes in JavaScript
Allocating the resulting array to avoid the overhead of push, parameter validation and locale specifics notwithstanding:
function generate_series(step) {
const dt = new Date(1970, 0, 1);
const rc = [];
while (dt.getDate() === 1) {
rc.push(dt.toLocaleTimeString('en-US'));
dt.setMinutes(dt.getMinutes() + step);
}
return rc;
}
Here's a demo snippet.
function generate_series(step) {
const dt = new Date(1970, 0, 1);
const rc = [];
while (dt.getDate() === 1) {
rc.push(dt.toLocaleTimeString('en-US'));
dt.setMinutes(dt.getMinutes() + step);
}
return rc;
}
function on_generate_series(step) {
const dt = new Date(1970, 0, 1);
const el = document.getElementById("series")
while (el.firstChild)
el.removeChild(el.firstChild);
const series = generate_series(step);
while (series.length > 0) {
let item = document.createElement("div");
item.innerText = series.shift();
el.appendChild(item);
}
}
<h1 id="title">24 Hour Minute Series</h1>
<input type="number" id="step" value="30" />
<input type="submit" id="byBtn" value="Generate Series" onclick="on_generate_series(parseInt(document.getElementById('step').value,10))" />
<div id="series">
</div>
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);