1
Fork 0
mirror of https://github.com/Steffo99/festa.git synced 2024-12-23 07:04:22 +00:00
festa/components/generic/renderers/datetime.tsx

47 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-06-08 15:31:34 +00:00
import { useTranslation } from "next-i18next"
2022-06-09 22:22:47 +00:00
type FestaMomentProps = {
2022-06-10 03:21:02 +00:00
date: Date | null,
2022-06-08 15:31:34 +00:00
}
2022-06-09 21:55:49 +00:00
/**
* Component that formats a {@link Date} to a machine-readable and human-readable HTML `time[datetime]` element.
*/
2022-06-11 03:08:49 +00:00
export const FestaMoment = ({ date }: FestaMomentProps) => {
2022-06-09 21:55:49 +00:00
const { t } = useTranslation()
2022-06-08 15:31:34 +00:00
2022-06-11 03:08:49 +00:00
if (date === null) {
return (
<span className="disabled">
{t("dateNull")}
</span>
)
}
if (Number.isNaN(date.getTime())) {
2022-06-08 15:31:34 +00:00
return (
<span className="disabled">
{t("dateNaN")}
</span>
)
}
2022-06-10 03:21:02 +00:00
const now = new Date()
const machine = date.toISOString()
let human
2022-06-11 03:08:49 +00:00
// If the date is less than 20 hours away, display just the time
if (date.getTime() - now.getTime() < (20 /*hours*/ * 60 /*minutes*/ * 60 /*seconds*/ * 1000 /*milliseconds*/)) {
2022-06-10 03:21:02 +00:00
human = date.toLocaleTimeString()
}
// Otherwise, display the full date
else {
human = date.toLocaleString()
}
2022-06-08 15:31:34 +00:00
return (
2022-06-10 03:21:02 +00:00
<time dateTime={machine}>
{human}
2022-06-08 15:31:34 +00:00
</time>
)
}