logseq-calendar/lib/month.ts
2023-08-23 15:21:01 -05:00

24 lines
648 B
TypeScript

import {
addDays,
endOfMonth,
getWeek,
isSameWeek,
startOfMonth,
} from "date-fns";
/**
* Return week bounds in a [closed, open) fashion
* The last week is not returned if it contains the next month's start date
* @param date
*/
export function weekBoundsOfMonth(date: Date): [number, number] {
const firstDayOfMonth = startOfMonth(date);
const startWeek = getWeek(firstDayOfMonth);
const lastDayOfMonth = endOfMonth(date);
const firstDayOfNextMonth = addDays(lastDayOfMonth, 1);
let endWeek = getWeek(lastDayOfMonth);
if (isSameWeek(lastDayOfMonth, firstDayOfNextMonth)) endWeek -= 1;
return [startWeek, endWeek];
}