-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathTime.astro
39 lines (31 loc) · 908 Bytes
/
Time.astro
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
---
const { datetime, relative } = Astro.props;
export interface Props {
datetime: string;
relative?: boolean;
}
---
<time datetime={datetime} data-relative={relative ? "true" : null}
><slot /></time
>
<script>
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import localizedFormat from "dayjs/plugin/localizedFormat";
dayjs.extend(relativeTime);
dayjs.extend(localizedFormat);
const timeElements = document.querySelectorAll("time");
for (const element of timeElements) {
const dateTime = element.getAttribute("datetime");
if (!dateTime) {
console.warn(element, "is missing datetime attribute");
continue;
}
const date = dayjs(dateTime);
if (element.getAttribute("data-relative") === "true") {
element.innerText = date.fromNow();
} else {
element.innerText = date.format("lll");
}
}
</script>