4

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

3
  • Should h be hours and m be minutes? Commented Sep 13, 2014 at 22:25
  • 1
    Maybe I'm mising the point, but instead of checking if the element is divideable by 15, just increment J by 15 in each loop: for (var j = minutes; j <= 59; j = j + 15 Commented Sep 13, 2014 at 22:28
  • @FrisoKluitenberg im not sure how that would work Commented Sep 13, 2014 at 22:30

7 Answers 7

15

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)
  ];
}
Sign up to request clarification or add additional context in comments.

3 Comments

i want it to keep track of the current time. Basically the time should start from whatever time is now until 24 hours
okay? So build this array, then find the array entry that is closes to your current time, and reorder the array (remove slice(0,current-1) and concat it to the end). The array itself still has nothing to do with hours and minutes =)
there is still an issue, if now is 3:40 PM the array will start from 3:00 instead of 3:45
3

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

1 Comment

if m = 50 and time is 3:43 your array starts from 4:00 PM rather then 3:45 PM
3

A one liner:

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

Comments

2

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());

Comments

1

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

3 Comments

this answer is very incomplete
It's simple.. 1. Get current timestamp 2. Find the closest quarter 3. Start adding to your array. The next date will be previous date + 15 minutes. Timestamp is a time in seconds - this is why I wrote 15 * 60.
cool, I wasn't suggesting you may not have had a viable approach but without a proper explanation the answer itself was poor quality compared to most
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.