Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Created February 17, 2020 02:49
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicksheffield/d02f9ee575c3b2d38a1ca49e39425a82 to your computer and use it in GitHub Desktop.
Save nicksheffield/d02f9ee575c3b2d38a1ca49e39425a82 to your computer and use it in GitHub Desktop.
Generate an array of time slots from a beginning to an end, skipping forward a certain amount of time each time
import { isBefore, setHours, setMinutes, setSeconds, addMinutes, setMilliseconds } from 'date-fns'
const setTime = (x, h = 0, m = 0, s = 0, ms = 0) => setHours(setMinutes(setSeconds(setMilliseconds(x, ms), s), m), h)
const from = setTime(new Date(), 9)
const to = setTime(new Date(), 17)
const step = (x) => addMinutes(x, 30)
const blocks = []
let cursor = from
while(isBefore(cursor, to)) {
blocks.push(cursor)
cursor = step(cursor)
}
console.log(blocks)
@MEGApixel23
Copy link

Saved my day, thanks!

@MEGApixel23
Copy link

MEGApixel23 commented Dec 20, 2020

Here's the same code in a form of the function + TS. I hope somebody finds it useful.

export const generateTimeSlots = (
  { start, end, interval, timeFormat }: { start: number, end: number, interval: number, timeFormat: string }
): string[] => {
  const setTime = (
    x: Date, h = 0, m = 0, s = 0, ms = 0
  ): Date => setHours(setMinutes(setSeconds(setMilliseconds(x, ms), s), m), h);

  const from = setTime(new Date(), start);
  const to = setTime(new Date(), end);
  const step = (x: Date): Date => addMinutes(x, interval);

  const blocks = [];

  let cursor = from;

  while (isBefore(cursor, to)) {
    blocks.push(formatDate(cursor, timeFormat));
    cursor = step(cursor);
  }

  return blocks;
};

@jordizle
Copy link

jordizle commented Jun 4, 2023

Thanks @MEGApixel23

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