Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code implementation to create an array of string for every X minutes throughout a full 24 hours. 

var times = []

  , periods = ['AM', 'PM']

  , hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

  , prop = null

  , hour = null

  , min = null; 

for (prop in periods) {

  for (hour in hours) {

    for (min = 0; min < 60; min += 5) {

      times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);

    }

  }

}

For example, for an interval of 5 minutes the array would be: 

['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']

Can anyone tell me is there a more efficient way to generate an array of times (as strings) for every X minutes in JavaScript?  

1 Answer

0 votes
by (19.7k points)

If the interval to be set in minutes [0-60], then you can create the date object in a single loop like below: 

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

Interested in Java? Check out this Java Certification by Intellipaat.   


 

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
asked May 9, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...