2023-06-09 18:21:18 +10:00
|
|
|
'use client';
|
|
|
|
|
|
|
|
|
|
import { HTMLAttributes, useEffect, useState } from 'react';
|
|
|
|
|
|
2023-09-12 14:29:27 +10:00
|
|
|
import { DateTime, DateTimeFormatOptions } 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;
|
2023-09-12 14:29:27 +10:00
|
|
|
format?: DateTimeFormatOptions;
|
2023-06-09 18:21:18 +10:00
|
|
|
};
|
|
|
|
|
|
2023-09-12 14:29:27 +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();
|
|
|
|
|
|
|
|
|
|
const [localeDate, setLocaleDate] = useState(() =>
|
|
|
|
|
DateTime.fromJSDate(new Date(date)).setLocale(locale).toLocaleString(format),
|
|
|
|
|
);
|
2023-06-09 18:21:18 +10:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-09-12 14:29:27 +10:00
|
|
|
setLocaleDate(DateTime.fromJSDate(new Date(date)).toLocaleString(format));
|
|
|
|
|
}, [date, format]);
|
2023-06-09 18:21:18 +10:00
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<span className={className} {...props}>
|
|
|
|
|
{localeDate}
|
|
|
|
|
</span>
|
|
|
|
|
);
|
|
|
|
|
};
|