2021-08-22 20:16:04 +02:00
|
|
|
import {
|
|
|
|
addDays,
|
|
|
|
addMonths,
|
|
|
|
addYears,
|
2021-09-05 17:43:14 +02:00
|
|
|
endOfMonth,
|
|
|
|
endOfWeek,
|
2021-08-22 20:16:04 +02:00
|
|
|
startOfMonth,
|
|
|
|
startOfWeek,
|
|
|
|
startOfYear,
|
|
|
|
} from 'date-fns'
|
2021-09-05 17:43:14 +02:00
|
|
|
import { utcToZonedTime } from 'date-fns-tz'
|
2021-08-22 20:16:04 +02:00
|
|
|
|
|
|
|
export const startDate = (
|
|
|
|
duration: string,
|
|
|
|
day: Date,
|
|
|
|
weekStartingMonday: boolean
|
|
|
|
): Date => {
|
|
|
|
switch (duration) {
|
|
|
|
case 'week':
|
|
|
|
return startOfWeek(day, { weekStartsOn: weekStartingMonday ? 1 : 0 })
|
|
|
|
case 'year':
|
|
|
|
return startOfYear(day)
|
|
|
|
case 'month':
|
|
|
|
return startOfMonth(day)
|
|
|
|
default:
|
|
|
|
throw new Error(
|
|
|
|
`Invalid duration, expected: "week", "month", "year", got: "${duration}"`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const incrementDate = (duration: string, day: Date): Date => {
|
|
|
|
switch (duration) {
|
|
|
|
case 'week':
|
|
|
|
return addDays(day, 7)
|
|
|
|
case 'year':
|
|
|
|
return addYears(day, 1)
|
|
|
|
case 'month':
|
|
|
|
return addMonths(day, 1)
|
|
|
|
default:
|
|
|
|
throw new Error(
|
|
|
|
`Invalid duration, expected: "week", "month", "year", got: "${duration}"`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2021-09-05 17:43:14 +02:00
|
|
|
|
|
|
|
export const getDateWithTZ = (dateInUTC: string, tz: string): Date => {
|
|
|
|
return utcToZonedTime(new Date(dateInUTC), tz)
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getCalendarStartAndEnd = (
|
|
|
|
date: Date,
|
|
|
|
weekStartingMonday: boolean
|
|
|
|
): Record<string, Date> => {
|
|
|
|
const monthStart = startOfMonth(date)
|
|
|
|
const monthEnd = endOfMonth(date)
|
|
|
|
const weekStartsOn = weekStartingMonday ? 1 : 0
|
|
|
|
return {
|
|
|
|
start: startOfWeek(monthStart, { weekStartsOn }),
|
|
|
|
end: endOfWeek(monthEnd),
|
|
|
|
}
|
|
|
|
}
|