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:
parent
00fbfeeb17
commit
e417e46dee
39
src/lib/date.ts
Normal file
39
src/lib/date.ts
Normal 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)});
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user