i am trying to create a time array, something like:
1:00
1:15
1:30
1:45
2:00
2:15
...
here is my code, what it does is that it starts the time from current time upwoards:
var timeArray = [];
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
for (var i = h; i <= 24; i++) {
for (var j = m; j <= 59; j++) {
if (j % 15 === 0) {
j = j === 0 ? '00' : j;
if (i >= 12) {
timeArray.push((i - 12) + ':' + j + ' PM');
} else {
timeArray.push(i + ':' + j + ' AM');
}
}
}
}
the problem is that is m
is over 46
, like var m = 50;
, then the array goes empty because j % 15
doesn't get 0 no more.
an ideas how to fix this?
thanks
If what you want is an array ["1:00", "1:15", ...] then why not just build that? It has nothing to do with "hours" and "minutes", only with "getting some obviously sequential numbers" right:
cost arr = [];
for (let i=0; i < 24; i++) {
for (let j=0; j < 4; j++) {
arr.push(`${i}:${j === 0 ? `00` : 15*j}`);
}
}
Done. Find your current time nearest a 15 minute block:
const d = new Date(),
h = d.getHours(),
m = 15 * Math.floor(d.getMinutes() / 15),
stamp = `${h}:${m === 0 ? `00` : m}`;
And just reorder the timeslots:
const pos = arr.indexOf(stamp);
let timelist = [];
if (pos > -1) {
timelist = [
...arr.slice(pos),
...arr.slice(0,pos)
];
}
Try this:
var timeArray = [],
d = new Date(),
h = d.getHours(),
m = d.getMinutes(),
meridiem = ['AM','PM'];
for (var i = h; i < 24; ++i) {
for (var j = i==h ? Math.ceil(m/15) : 0; j < 4; ++j) {
timeArray.push(i%12 + ':' + (j*15||'00') + ' ' + meridiem[i/12|0]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With