logseq-calendar/lib/month.ts

25 lines
648 B
TypeScript
Raw Normal View History

2023-08-23 20:21:01 +00:00
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];
}