Skip to content

Instantly share code, notes, and snippets.

@kouameYao
Created March 25, 2026 18:16
Show Gist options
  • Select an option

  • Save kouameYao/3285388441787e0cf9c24cf9c52d48a0 to your computer and use it in GitHub Desktop.

Select an option

Save kouameYao/3285388441787e0cf9c24cf9c52d48a0 to your computer and use it in GitHub Desktop.
import type { Locale } from 'date-fns';
import { format, formatRelative, isSameDay, isToday, isYesterday, subDays } from 'date-fns';
import { fr } from 'date-fns/locale';
import { isNaN } from 'lodash';
const formatRelativeLocale = {
lastWeek: 'eeee \'dernier,\' HH:mm',
yesterday: '\'Hier,\' HH:mm',
today: '\'Aujourd\'hui,\' HH:mm',
tomorrow: '\'Demain,\' HH:mm',
nextWeek: 'eeee\',\' HH:mm',
other: '',
};
const locale = {
...fr,
formatRelative: token => formatRelativeLocale[token],
} satisfies Pick<Locale, keyof Locale>;
export function formatDate(dateString: string | undefined): string {
if (!dateString) {
return '-';
}
const date = new Date(dateString);
if (isNaN(date.getTime())) {
return '-';
}
const now = new Date();
if (isSameDay(date, subDays(now, 2))) {
return `Avant-hier, ${format(date, 'HH:mm')}`;
}
if (!isToday(date) && !isYesterday(date) && date < now) {
if (date.getFullYear() === now.getFullYear()) {
return format(date, 'd MMMM\',\' HH:mm', { locale: fr });
}
return format(date, 'd MMMM yyyy\',\' HH:mm', { locale: fr });
}
return formatRelative(date, now, { locale });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment