Files
sign/apps/web/src/components/formatter/locale-date.tsx

50 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-06-09 18:21:18 +10:00
'use client';
import type { HTMLAttributes } from 'react';
2024-02-15 18:20:10 +11:00
import { useCallback, useEffect, useState } from 'react';
2023-06-09 18:21:18 +10:00
import type { DateTimeFormatOptions } from 'luxon';
import { DateTime } from 'luxon';
import { useLocale } from '@documenso/lib/client-only/providers/locale';
2023-06-09 18:21:18 +10:00
export type LocaleDateProps = HTMLAttributes<HTMLSpanElement> & {
date: string | number | Date;
2024-02-15 18:20:10 +11:00
format?: DateTimeFormatOptions | string;
2023-06-09 18:21:18 +10:00
};
/**
* Formats the date based on the user locale.
*
* Will use the estimated locale from the user headers on SSR, then will use
* the client browser locale once mounted.
*/
export const LocaleDate = ({ className, date, format, ...props }: LocaleDateProps) => {
const { locale } = useLocale();
2024-02-15 18:20:10 +11:00
const formatDateTime = useCallback(
(date: DateTime) => {
if (typeof format === 'string') {
return date.toFormat(format);
}
return date.toLocaleString(format);
},
[format],
);
const [localeDate, setLocaleDate] = useState(() =>
2024-02-15 18:20:10 +11:00
formatDateTime(DateTime.fromJSDate(new Date(date)).setLocale(locale)),
);
2023-06-09 18:21:18 +10:00
useEffect(() => {
2024-02-15 18:20:10 +11:00
setLocaleDate(formatDateTime(DateTime.fromJSDate(new Date(date))));
}, [date, format, formatDateTime]);
2023-06-09 18:21:18 +10:00
return (
<span className={className} {...props}>
{localeDate}
</span>
);
};