From e417e46deed7f3330760d426ecd9977397ce28c9 Mon Sep 17 00:00:00 2001 From: Mathis Date: Fri, 27 Sep 2024 16:57:37 +0200 Subject: [PATCH] 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. --- src/lib/date.ts | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/lib/date.ts diff --git a/src/lib/date.ts b/src/lib/date.ts new file mode 100644 index 0000000..13a5a2e --- /dev/null +++ b/src/lib/date.ts @@ -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)}); + } +} \ No newline at end of file