Fake Account
Fake Account

Reputation: 94

Make time in loop with increment number

I have to print time (just hours).

Expected Result:-

0:00 AM - 1:00 AM,

1:00 AM - 2:00 AM so on to

12:00 PM - 13:00 PM so on to

20:00 PM - 21:00 PM till

23:00 PM - 24:00 PM.

What i did

let time = [];
for (let i = 0; i <= 23; i++) {
  /*
   ** padStart function which adds 0 to the start **
   ** to make it two digit if the time is in 1 digit. **
   ** it adds 0 to single digit numbers(1 will become 01, 2 will become 02 etc) **
   */
  let timeString = "";
  timeString += (i + ":00").padStart(2, "0") + ((i < 12) ? " AM - " : " PM - ") + (i + 1 + ":00").padStart(2, "0") + (((i + 1) >= 12) ? " PM " : " AM ");
  time.push(timeString);
}

In short:- Please suggest any other effective way I could have done this? Thanks.

Upvotes: 1

Views: 395

Answers (3)

Barrard
Barrard

Reputation: 2043

function makeTime(hr, min, date, amPM) {
  hr = amPM === "AM" ? hr : hr + 12;
  let time = new Date();
  time = new Date(time).setHours(hr);
  time = new Date(time).setMinutes(min);
  time = new Date(time).setDate(date);
  time = new Date(time).setSeconds(0);
  return new Date(time).getTime();
}

  function makeTimes(_start, increment, _end) {
    const times = [];
    const start = makeTime(_start.hr, _start.min, _start.date, _start.amPM);
    const end = makeTime(_end.hr, _end.min, _end.date, _end.amPM);
    times.push({
        datetime: start,
        local: new Date(start).toLocaleString(),
    });
    let nextTime = start + increment * 1000 * 60;
    while (nextTime < end) {
        times.push({
            datetime: nextTime,
            local: new Date(nextTime).toLocaleString(),
        });
        nextTime = nextTime + increment * 1000 * 60;
    }

    return times;
  }

makeTimes(
        { hr: 6, min: 30, date: 7, amPM: "AM" },
        5,
        { hr: 1, min: 0, date: 7, amPM: "PM" }

enter image description here

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386634

You could take a function for formatting the time and pad the time without colon and zeroes first and then add the rest.

const
    format = time => time.toString().padStart(2, 0) + ":00 " + (time < 12 ? "AM" : "PM");

let time = [];

for (let i = 0; i < 24; i++) {
    time.push(format(i) + ' - ' + format(i + 1));
}

console.log(time);

A shorter approach with Array.from

const
    format = time => time.toString().padStart(2, 0) + ":00 " + (time < 12 ? "AM" : "PM");

let time = Array.from(
        { length: 24 },
        (_, i) => format(i) + ' - ' + format(i + 1)
    );

console.log(time);

Upvotes: 2

Justinas
Justinas

Reputation: 43479

Use momentjs and loop hours needed to convert to proper times

let currentTime = moment('00:00:00', 'HH:mm:ss');
let time = [];
for (let i = 0; i <= 23; i++) {
  time.push(
      currentTime.format('HH:mmP') +
      ' - ' +
      currentTime.add(1, 'hour').format('HH:mmP')
  );
}

Upvotes: 1

Related Questions