0

I need to display hour from specific hour until specific hour.

Assume I need the hour from 03-Jul-2021 07:00 until 04-Jul-2021 07:00.

var date = new Date;
var hour = date.getHours();

var getHour = []
for( var i=7; i<hour; i++ ) {
  getHour.push(i+":00");
}

console.log(getHour);

How can I do that?

So the result should be:

07:00
08:00
09:00
10:00
11:00
12:00
13:00
14:00
15:00
16:00
17:00
18:00
19:00
20:00
21:00
22:00
23:00
00:00
01:00
02:00
03:00
04:00
05:00
06:00
07:00

Any idea how to do that?

pavel
  • 26,538
  • 10
  • 45
  • 61
HiDayurie Dave
  • 1,791
  • 2
  • 17
  • 45

2 Answers2

1

Here is one way

  1. It does not hardcode the time in the loop
  2. It pads the hours

Missing: handling DST switching. We can use the .getTimezoneOffset() if we want to have a list that has the correct times across DST

const anHour = 60*60*1000;
const getTimes = (start, end) => {
  const hours = [];
  for (let i = start, n = end.getTime(); i.getTime() <= n; i.setTime(i.getTime()+anHour)) hours.push(`${String(i.getHours()).padStart(2,"0")}:00`);
  return hours;
};


let startDate = new Date(2021, 6, 3, 7, 0, 0, 0);
let endDate = new Date(2021, 6, 4, 7, 0, 0, 0);
console.log(getTimes(startDate, endDate));

// If you do not need to specify dates and times, then have a static array of 
const times = ["07:00",  "08:00",  "09:00",  "10:00",  "11:00",  "12:00",  "13:00", "14:00",  "15:00", "16:00",  "17:00",  "18:00",  "19:00",  "20:00", "21:00",  "22:00",  "23:00",  "00:00",  "01:00",  "02:00",  "03:00",  "04:00",  "05:00",  "06:00",  "07:00" ];

Handling DST would need something like
How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

If I understand your question, it should be something like

var date = new Date;
var hour = date.getHours();

var getHour = []
for (var i = 0; i < 25; i++) {
  getHour.push((hour + i) % 24 + ":00");
}

console.log(getHour); // 8:00, 9:00, ... 8:00
mplungjan
  • 169,008
  • 28
  • 173
  • 236
pavel
  • 26,538
  • 10
  • 45
  • 61