|
1
|
import { format, formatDistance, sub } from "date-fns" |
|
2
|
import { enUS } from "date-fns/locale" |
|
3
|
import { useTranslation } from "react-i18next" |
|
4
|
|
|
5
|
import { languages } from "../i18n/languages" |
|
6
|
|
|
7
|
// TODO: We rely on the current language to determine the date locale. This is not ideal, as we use en-US for the english translation. |
|
8
|
// We either need to also have an en-GB translation or we need to separate the date locale from the translation language. |
|
9
|
export const useDate = () => { |
|
10
|
const { i18n } = useTranslation() |
|
11
|
|
|
12
|
const locale = |
|
13
|
languages.find((l) => l.code === i18n.language)?.date_locale || enUS |
|
14
|
|
|
15
|
const getFullDate = ({ |
|
16
|
date, |
|
17
|
includeTime = false, |
|
18
|
}: { |
|
19
|
date: string | Date |
|
20
|
includeTime?: boolean |
|
21
|
}) => { |
|
22
|
const ensuredDate = new Date(date) |
|
23
|
|
|
24
|
if (isNaN(ensuredDate.getTime())) { |
|
25
|
return "" |
|
26
|
} |
|
27
|
|
|
28
|
const timeFormat = includeTime ? "p" : "" |
|
29
|
|
|
30
|
return format(ensuredDate, `PP ${timeFormat}`, { |
|
31
|
locale, |
|
32
|
}) |
|
33
|
} |
|
34
|
|
|
35
|
function getRelativeDate(date: string | Date): string { |
|
36
|
const now = new Date() |
|
37
|
|
|
38
|
return formatDistance(sub(new Date(date), { minutes: 0 }), now, { |
|
39
|
addSuffix: true, |
|
40
|
locale, |
|
41
|
}) |
|
42
|
} |
|
43
|
|
|
44
|
return { |
|
45
|
getFullDate, |
|
46
|
getRelativeDate, |
|
47
|
} |
|
48
|
} |