Skip to content

Instantly share code, notes, and snippets.

@indexzero
Created June 29, 2017 18:33
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save indexzero/6261ad9292c78cf3c5aa69265e2422bf to your computer and use it in GitHub Desktop.
Save indexzero/6261ad9292c78cf3c5aa69265e2422bf to your computer and use it in GitHub Desktop.
Generate a 24 hour range of 30-minute time intervals that are i18n compatible
let items = [];
for (var hour = 0; hour < 24; hour++) {
items.push([hour, 0]);
items.push([hour, 30]);
}
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: false
});
const range = items.map(time => {
const [hour, minute] = time;
date.setHours(hour);
date.setMinutes(minute);
return formatter.format(date);
});
console.dir(range);
@ridvanaltun
Copy link

const generateHoursInterval = (
  startHourInMinute,
  endHourInMinute,
  interval,
) => {
  const times = [];

  for (let i = 0; startHourInMinute < 24 * 60; i++) {
    if (startHourInMinute > endHourInMinute) break;

    var hh = Math.floor(startHourInMinute / 60); // getting hours of day in 0-24 format

    var mm = startHourInMinute % 60; // getting minutes of the hour in 0-55 format

    times[i] = ('0' + (hh % 24)).slice(-2) + ':' + ('0' + mm).slice(-2);

    startHourInMinute = startHourInMinute + interval;
  }

  return times;
};

const interval = 30; //minutes interval

const startDate = 60 * 7; // start time in minutes

const endDate = 60 * 21; // end time in minutes

const foo = generateHoursInterval(startDate, endDate, interval);

console.log(foo);
// ["07:00", "07:30", "08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00"]

@sumonst21
Copy link

@RaviTr-web
Copy link

Awesome, very useful

@outOFFspace
Copy link

outOFFspace commented Aug 20, 2023

mmm image

Use { hourCycle: 'h23' } instead of { hour12: false }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment