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