Raw
1 import { format, formatDistance, sub } from "date-fns";
2 import { enUS } from "date-fns/locale";
3
4 export const useDate = () => {
5 const locale = enUS;
6
7 const getFullDate = ({
8 date,
9 includeTime = false,
10 }: {
11 date: string | Date;
12 includeTime?: boolean;
13 }) => {
14 const ensuredDate = new Date(date);
15
16 if (isNaN(ensuredDate.getTime())) {
17 return "";
18 }
19
20 const timeFormat = includeTime ? "p" : "";
21
22 return format(ensuredDate, `PP ${timeFormat}`, {
23 locale,
24 });
25 };
26
27 function getRelativeDate(date: string | Date): string {
28 const now = new Date();
29
30 return formatDistance(sub(new Date(date), { minutes: 0 }), now, {
31 addSuffix: true,
32 locale,
33 });
34 }
35
36 return {
37 getFullDate,
38 getRelativeDate,
39 };
40 };