Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array with hours and minutes in javascript?

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

like image 431
Patrioticcow Avatar asked Sep 20 '25 02:09

Patrioticcow


2 Answers

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)
  ];
}
like image 55
Mike 'Pomax' Kamermans Avatar answered Sep 22 '25 17:09

Mike 'Pomax' Kamermans


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]);
    }
}
like image 37
Oriol Avatar answered Sep 22 '25 15:09

Oriol