feat(lib): add date formatting utilities

Introducing `DateFormatter` class with methods for formatted date output, relative date calculations, and distance to current date using `date-fns` and localization support for French and English.
This commit is contained in:
Mathis H (Avnyr) 2024-09-27 16:57:37 +02:00
parent 00fbfeeb17
commit e417e46dee
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

39
src/lib/date.ts Normal file
View File

@ -0,0 +1,39 @@
import {format, formatDistance, formatRelative, subDays} from "date-fns";
import {fr, enUS} from "date-fns/locale";
interface DateOptions {
/**
* A string template used for formatting output.
* This template can include placeholders that are replaced with specific data at runtime.
* The format of the placeholders must be compatible with the formatting mechanism used.
*
* @example `PPPP | PPPPpppp`
*
* @type {string}
*/
formatTemplate: string;
locale: "fr" | "enUS";
}
export class DateFormatter {
private static readonly localeMapping = {
fr: fr,
enUS: enUS,
};
private static getLocale(locale: "fr" | "enUS") {
return DateFormatter.localeMapping[locale];
}
generateFormattedDate(date: Date, options: DateOptions): string {
return format(date, options.formatTemplate, {locale: DateFormatter.getLocale(options.locale)});
}
generateRelativeDate(date: Date, baseDate: Date, options: DateOptions): string {
return formatRelative(date, baseDate, {locale: DateFormatter.getLocale(options.locale)});
}
generateDistanceToNow(date: Date, options: DateOptions): string {
return formatDistance(date, new Date(), {locale: DateFormatter.getLocale(options.locale)});
}
}