Files
neuf-www/web/src/lib/date.ts

35 lines
1.1 KiB
TypeScript

import { isToday, isAfter, parse } from "date-fns";
import { nb } from "date-fns/locale";
import { toZonedTime, format} from "date-fns-tz";
const timeZone = "Europe/Oslo";
export const commonDateFormat = "dd.MM.yyyy 'kl.' HH:mm";
export function toLocalTime(date: Date | string | number) {
return toZonedTime(date, timeZone);
}
export function formatDate(date: Date | string | number, formatStr: string) {
return format(toLocalTime(date), formatStr, { timeZone, locale: nb });
}
export function formatYearMonth(yearMonth: string) {
// full name of month if year is current year, otherwise name of month + year
const parsed = parse(yearMonth, "yyyy-MM", new Date());
if (parsed.getFullYear === new Date().getFullYear) {
return formatDate(parsed, "MMMM");
}
return formatDate(parsed, "MMMM yyyy");
}
export function isTodayOrFuture(
date: Date | string | number,
timeZone = "UTC"
) {
const now = new Date();
const zonedNow = toZonedTime(now, timeZone);
const zonedDate = toLocalTime(date);
return isToday(zonedDate) || isAfter(zonedDate, zonedNow);
}