Created
February 17, 2020 02:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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;
};
Thanks @MEGApixel23
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saved my day, thanks!