-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
Raw Code
// ===============================================
// Parsing
// ===============================================
/**
* Given an unknown value, try to parse it as a Date and return it.
* If it fails, throw an error.
*/
export function parseDate(rawInput: unknown) {
try {
const date = new Date(rawInput as any);
if (!isValid(date)) {
throw new Error('Invalid date');
}
return date;
} catch (error) {
throw new Error(`Cannot create Date object from "${String(rawInput)}". Reason: ${error}`);
}
}
// ===============================================
// Create Time Range
// ===============================================
/** Create an array of time ranges in weeks */
export function createTimeRangeInWeek(from: Date, to: Date) {
return eachWeekOfInterval({ start: from, end: to })
.map(weekStartDate => ({
weekLabel: formatWeekKey(weekStartDate),
weekStartDate,
}));
}
/** Create an array of time ranges in month */
export function createTimeRangeInMonth(from: Date, to: Date) {
return eachMonthOfInterval({ start: from, end: to })
.map(monthStartDate => ({
monthLabel: formatMonthKey(monthStartDate),
monthStartDate,
}));
}
export function createTimeRangeInYear(from: Date, to: Date) {
return eachYearOfInterval({ start: from, end: to })
.map(yearStartDate => ({
yearLabel: formatYearKey(yearStartDate),
yearStartDate,
}));
}
// ===============================================
// Format Date
// ===============================================
export type WeekKey = ReturnType<typeof formatWeekKey>;
export function formatWeekKey(weekFirstDay: Date) {
return formatDate(weekFirstDay, "yyyy-'W'II");
}
export type MonthKey = ReturnType<typeof formatMonthKey>;
export function formatMonthKey(monthFirstDay: Date) {
return formatDate(monthFirstDay, "yyyy-MM");
}
export type YearKey = ReturnType<typeof formatYearKey>;
export function formatYearKey(yearFirstDay: Date) {
return formatDate(yearFirstDay, "yyyy");
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels