Skip to content

Instantly share code, notes, and snippets.

@space11
Created May 21, 2024 10:56
Show Gist options
  • Save space11/7f543cf9e080f3fe60abf00e61de7988 to your computer and use it in GitHub Desktop.
Save space11/7f543cf9e080f3fe60abf00e61de7988 to your computer and use it in GitHub Desktop.
Generate to date ranges
// Credit to https://github.com/iamkun/dayjs/issues/1162?fbclid=IwAR2swchqUZ3ovxzj0MeL7CVbZpN8KVnWx-LgLwIY80UNuGSQ4TRnQC3wIfQ#issuecomment-1694654608
import type { Dayjs, ManipulateType } from 'dayjs';
/**
* Create a range of Day.js dates between a start and end date.
*
* ```js
* dayjsRange(dayjs('2021-04-03'), dayjs('2021-04-05'), 'day');
* // => [dayjs('2021-04-03'), dayjs('2021-04-04'), dayjs('2021-04-05')]
* ```
*/
export function dayjsRange(start: Dayjs, end: Dayjs, unit: ManipulateType) {
const range = [];
let current = start;
while (!current.isAfter(end)) {
range.push(current);
current = current.add(1, unit);
}
return range;
}
/**
* Create a range of Day.js dates between a start and end date.
*
* ```js
* getDaysBetween(dayjs('2021-04-03'), dayjs('2021-04-05'));
* // => [dayjs('2021-04-03'), dayjs('2021-04-04'), dayjs('2021-04-05')]
* ```
*/
export function getDaysBetween(start: Dayjs, end: Dayjs) {
const range = [];
let current = start;
while (!current.isAfter(end)) {
range.push(current);
current = current.add(1, 'days');
}
return range;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment