简体   繁体   中英

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

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:

var arr = [], i, j;
for(i=0; i<24; i++) {
  for(j=0; j<4; j++) {
    arr.push(i + ":" + (j===0 ? "00" : 15*j) );
  }
}

done. Find your current time nearest a 15 minute block:

var d = new Date(),
    h = d.getHours(),
    m = 15 * Math.floor(d.getMinutes()/15),
    stamp = h + ":" + (m === 0 ? "00" : m);

And just reorder the timeslots:

var pos = arr.indexOf(stamp),
    timelist = arr.slice(pos).concat(arr.slice(0,pos));

I think you can do it simpler by using JavaScript Date API and by a simple trick.

In loop all you need is to add 15 * 60 seconds (one quarter of an hour) to timestamp and print. Only calculate the closest full time (11:57 -> 12:00) at the beginning, then add as much quarters as you need.

Please see the code:

var date, array = [];
date = new Date();

// Here we will find the closest time
// If it's 13:09 we'll iterate to 13:15 and stop
//
// We'll iterate fifteen times in the worst case scenario
while (date.getMinutes() % 15 !== 0) {
    date.setMinutes ( date.getMinutes() + 1 );
}

// A whole day has 24 * 4 quarters of an hour
// Let's iterate using for loop
for (var i = 0; i < 24 * 4; i++) {
    array.push(date.getHours() + ':' + date.getMinutes());
    date.setMinutes ( date.getMinutes() + 15);
}

console.log(array);

// Now in Poland it's 18:10 so the result is an array of 96 elements 
// ["18:15", "18:30", "18:45", "19:0", ... "17:30", "17:45", "18:0"]
// As you may noticed, there is a need to format date when it's a full hour.
// We have 18:0 but we expect 18:00. This will be more understandable for users.
// We can open another discussion to find the best way to do that ;)

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]);
    }
}

一个班轮:

 const arr = Array(24 * 4).fill(0).map((_, i) => { return ('0' + ~~(i / 4) + ': 0' + 60 * (i / 4 % 1)).replace(/\\d(\\d\\d)/g, '$1') });

My solution is a bit long-winded, but it also gives you the associated time value which could be useful in some cases.

 const getTimeBlocks = () => { const minutesInDay = 1440; const timeBlocksArr = [{ timeString: '12:00 AM', timeValue: '0' }]; for (let i = 30; i <= minutesInDay - 30; i += 30) { const halfHourInLoop = i / 60; let formattedBlock = String(halfHourInLoop); const hour = formattedBlock.split('.')[0]; const minute = i % 60 === 0 ? '00' : '30'; formattedBlock = `${hour}:${minute}`; const today = new Date(); const timeString = new Date( today.getFullYear(), today.getMonth(), today.getDate(), Number(hour), Number(minute), ); timeBlocksArr.push({ timeString: timeString.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }), timeValue: formattedBlock, }); } return timeBlocksArr; }; console.log(getTimeBlocks());

The main problem is that the inner loop ( j ) starts at m variable, and that probably is not zero at most times of the day. So for the first loop of i that is ok. But for next loop you want that to be zero. You can fix that by assigning that m variable to zero at the end of the i for loop.

And try not to mix the variables that are for calculations (integers) with the ones you use for formatting the time (strings). You are doing that for j in here:

j = j === 0 ? '00' : j;

Here is the code I'd use (I also fixed the AM for 12 midnight and skiped most iteration of j by simply incrementing by 15 instead of by 1):

var timeArray = [];
var d = new Date();
var h = d.getHours();
var m = Math.ceil(d.getMinutes() / 15) * 15;

for (var i = h; i <= 24; i++) {
  for (var j = m; j <= 59; j += 15) {
    var mf = j === 0 ? '00' : j;
    var hf = i >= 12 ? (i - 12) : i;
    var amPm = i >= 12 && i < 24 ? 'PM' : 'AM';
    timeArray.push(hf + ':' + mf + ' ' +  amPm);
  }
  m = 0;
}

Try this

var timeArray = [];
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();

for(var i=0; i< 24; i++){
    for(m = (m + 15 - m%15)%60; m < 60; m = m + 15){
        timeArray.push(h + ':' + m);
    }
    h = (h+1) % 24;
    timeArray.push(h + ':' + '00');
}

console.log(timeArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM