logseq-calendar/lib/date.ts
2023-08-24 13:37:23 -04:00

38 lines
998 B
TypeScript

import {
addDays,
endOfMonth,
getWeek,
isSameWeek,
startOfMonth,
startOfWeek,
subDays,
} from "date-fns";
export const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
/**
* 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): [Date, Date] {
const firstDayOfMonth = startOfMonth(date);
const startWeek = startOfWeek(firstDayOfMonth);
const lastDayOfMonth = endOfMonth(date);
const firstDayOfNextMonth = addDays(lastDayOfMonth, 1);
let endWeek = startOfWeek(lastDayOfMonth);
if (isSameWeek(lastDayOfMonth, firstDayOfNextMonth))
endWeek = subDays(endWeek, 7);
return [startWeek, endWeek];
}
export function weekString(date: Date): string {
return `${getWeek(date)}/${date.getFullYear()}`;
}
export function monthNameOf(date: Date): string {
return date.toLocaleDateString("default", { month: "long" });
}