92 lines
2.4 KiB
TypeScript
92 lines
2.4 KiB
TypeScript
import { format, isToday, isTomorrow, formatDistance } from 'date-fns';
|
|
import { fr } from 'date-fns/locale';
|
|
|
|
/**
|
|
* Format a date as a short date string (e.g., "15 jun.")
|
|
*/
|
|
export function formatShortDate(date: Date | string): string {
|
|
const dateObj = date instanceof Date ? date : new Date(date);
|
|
return format(dateObj, 'd MMM', { locale: fr });
|
|
}
|
|
|
|
/**
|
|
* Format a time as a 24-hour time string (e.g., "14:30")
|
|
*/
|
|
export function formatTime(date: Date | string): string {
|
|
const dateObj = date instanceof Date ? date : new Date(date);
|
|
return format(dateObj, 'HH:mm', { locale: fr });
|
|
}
|
|
|
|
/**
|
|
* Format a date as a relative string (e.g., "Today", "Tomorrow", "Monday")
|
|
*/
|
|
export function formatRelativeDate(date: Date | string, includeTime: boolean = false): string {
|
|
const dateObj = date instanceof Date ? date : new Date(date);
|
|
|
|
let dateString = "";
|
|
|
|
if (isToday(dateObj)) {
|
|
dateString = "Today";
|
|
} else if (isTomorrow(dateObj)) {
|
|
dateString = "Tomorrow";
|
|
} else {
|
|
dateString = format(dateObj, 'EEEE d MMMM', { locale: fr });
|
|
}
|
|
|
|
if (includeTime) {
|
|
dateString += ` · ${format(dateObj, 'HH:mm', { locale: fr })}`;
|
|
}
|
|
|
|
return dateString;
|
|
}
|
|
|
|
/**
|
|
* Format a date as a relative time ago (e.g., "5 minutes ago", "2 hours ago")
|
|
*/
|
|
export function formatTimeAgo(date: Date | string): string {
|
|
const dateObj = date instanceof Date ? date : new Date(date);
|
|
return formatDistance(dateObj, new Date(), {
|
|
addSuffix: true,
|
|
locale: fr,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Format a date for display in isoformat
|
|
*/
|
|
export function formatISODate(date: Date | string): string {
|
|
const dateObj = date instanceof Date ? date : new Date(date);
|
|
return dateObj.toISOString();
|
|
}
|
|
|
|
/**
|
|
* Check if a date string is valid
|
|
*/
|
|
export function isValidDateString(dateStr: string): boolean {
|
|
if (!dateStr || dateStr === '0000-00-00 00:00:00') return false;
|
|
|
|
try {
|
|
const date = new Date(dateStr);
|
|
return !isNaN(date.getTime());
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a formatted month name
|
|
*/
|
|
export function getMonthName(month: number, short: boolean = false): string {
|
|
const date = new Date();
|
|
date.setMonth(month);
|
|
return format(date, short ? 'MMM' : 'MMMM', { locale: fr });
|
|
}
|
|
|
|
/**
|
|
* Get a formatted day name
|
|
*/
|
|
export function getDayName(day: number, short: boolean = false): string {
|
|
const date = new Date();
|
|
date.setDate(day);
|
|
return format(date, short ? 'EEE' : 'EEEE', { locale: fr });
|
|
}
|