Files
pfadi-bussle/helpers/date.ts
Thomas Ruoff 08398bd5a6 update eslint
2025-03-31 22:30:40 +02:00

87 lines
1.9 KiB
TypeScript

import { parse, format, addDays, subDays } 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: Date
endDate: Date
endDateExclusive?: boolean
}): string[] {
let currentDay = new Date(startDate.getTime())
const days = [dateFormatBackend(currentDay)]
if (!endDate) {
return days
}
const inclusiveEndDate = endDateExclusive ? subDays(endDate, 1) : 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 (!Number.isNaN(date.getTime())) {
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)
}