mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 06:27:11 +01:00
83 lines
1.8 KiB
TypeScript
83 lines
1.8 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 (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)
|
|
}
|