65 lines
1.9 KiB
TypeScript
65 lines
1.9 KiB
TypeScript
/**
|
|
* Date formatting and calculation utilities for Swedish locale (sv-SE).
|
|
* All functions use ISO 8601 format for input (YYYY-MM-DD) and Intl API for display.
|
|
*/
|
|
|
|
/**
|
|
* Format a date for display (e.g. "1 juni 2026" in Swedish).
|
|
* Accepts ISO string or Date object.
|
|
*/
|
|
export function formatDateForDisplay(date: string | Date): string {
|
|
const d = typeof date === 'string' ? new Date(date + 'T00:00:00Z') : date
|
|
if (!isValidDate(d)) return ''
|
|
const formatter = new Intl.DateTimeFormat('sv-SE', {
|
|
year: 'numeric',
|
|
month: 'long',
|
|
day: 'numeric',
|
|
})
|
|
return formatter.format(d)
|
|
}
|
|
|
|
/**
|
|
* Format a date for HTML input value (e.g. "2026-06-01").
|
|
* Accepts ISO string or Date object.
|
|
*/
|
|
export function formatDateForInput(date: string | Date): string {
|
|
const d = typeof date === 'string' ? new Date(date + 'T00:00:00Z') : date
|
|
if (!isValidDate(d)) return ''
|
|
const year = d.getUTCFullYear()
|
|
const month = String(d.getUTCMonth() + 1).padStart(2, '0')
|
|
const day = String(d.getUTCDate()).padStart(2, '0')
|
|
return `${year}-${month}-${day}`
|
|
}
|
|
|
|
/**
|
|
* Parse an ISO date string (YYYY-MM-DD) to a Date object.
|
|
*/
|
|
export function parseInputDate(value: string): Date {
|
|
return new Date(value + 'T00:00:00Z')
|
|
}
|
|
|
|
/**
|
|
* Type guard: check if a value is a valid date.
|
|
*/
|
|
export function isValidDate(date: any): boolean {
|
|
return date instanceof Date && !isNaN(date.getTime())
|
|
}
|
|
|
|
/**
|
|
* Get the Swedish day name (e.g. "Fredag").
|
|
*/
|
|
export function getDayName(date: Date): string {
|
|
if (!isValidDate(date)) return ''
|
|
const formatter = new Intl.DateTimeFormat('sv-SE', { weekday: 'long' })
|
|
return formatter.format(date)
|
|
}
|
|
|
|
/**
|
|
* Get the Swedish month name (e.g. "Juni").
|
|
*/
|
|
export function getMonthName(date: Date): string {
|
|
if (!isValidDate(date)) return ''
|
|
const formatter = new Intl.DateTimeFormat('sv-SE', { month: 'long' })
|
|
return formatter.format(date)
|
|
}
|