Files
pfadi-bussle/helpers/date.ts
2022-10-11 11:43:32 +02:00

92 lines
2.2 KiB
TypeScript

import { parse, format, addDays, subDays, differenceInDays } from 'date-fns'
import { utcToZonedTime } from 'date-fns-tz'
const FRONTEND_FORMAT = 'dd.MM.yyyy'
const BACKEND_FORMAT = 'yyyy-MM-dd'
export function daysFormatFrontend(days: string[]): string {
if (days.length === 0) {
return ''
}
if (days.length === 1) {
return dateFormatFrontend(new Date(days[0]))
}
return [days[0], days.slice(-1)]
.map((day: string) => dateFormatFrontend(new Date(day)))
.join('-')
}
export function getDays({
startDate,
endDate,
endDateExclusive = false,
}: {
startDate: string,
endDate: string,
endDateExclusive?: boolean
}): string[] {
let currentDay = new Date(startDate);
const days = [dateFormatBackend(currentDay)]
if (!endDate) {
return days
}
const inclusiveEndDate = endDateExclusive ? subDays(new Date(endDate), 1) : new Date(endDate)
while (currentDay < inclusiveEndDate) {
currentDay = addDays(currentDay, 1)
days.push(dateFormatBackend(currentDay))
}
return days
}
function dateFormat(date: Date, formatString: string): string {
if (!date) {
return null
}
return format(date, formatString)
}
export function dateFormatBackend(date: Date): string {
return dateFormat(date, BACKEND_FORMAT)
}
export function dateFormatFrontend(date: Date): string {
return dateFormat(date, FRONTEND_FORMAT)
}
function dateParse(input: string, formatString: string): Date {
const date = parse(input, formatString, new Date())
if (date.getTime() !== NaN) {
return date
}
return null
}
export function dateParseFrontend(input: string): Date {
return dateParse(input, FRONTEND_FORMAT)
}
export function dateParseBackend(input: string): Date {
return dateParse(input, BACKEND_FORMAT)
}
export function nowInTz(timezone = 'Europe/Berlin'): Date {
const now = new Date()
return utcToZonedTime(now, timezone)
}
export function getNextDay(date: Date) {
return addDays(date, 1)
}
export function getDayCount({ startDate, endDate }: { startDate: string, endDate: string }) {
// TODO: check if this actually works as expected
return differenceInDays(new Date(startDate), new Date(endDate)) + 1 // add one as it only counts full days;
}