Last active
March 11, 2024 09:53
-
-
Save gocs/9d4b23d72193aca646ff58ff8e0b3158 to your computer and use it in GitHub Desktop.
ISO 8601 to local and relative datetime plus svelte ticker component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { onMount } from "svelte"; | |
import { toAutoLocalDate, toRelativeTime } from "./time"; | |
export let start: string; | |
let date: string; | |
onMount(() => { | |
let interval: number = setInterval(() => { | |
date = toRelativeTime(start); | |
}, 1000); | |
return () => clearInterval(interval); | |
}); | |
</script> | |
<time datetime={start} title={toAutoLocalDate(start)}> | |
{date} | |
</time> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toAutoLocalDate(date: string): string { | |
return Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale).format(new Date(date)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const lang = Intl.DateTimeFormat().resolvedOptions().locale | |
const MINUTE_MILLISECONDS = 1000 * 60; | |
const HOUR_MILLISECONDS = MINUTE_MILLISECONDS * 60; | |
const DAY_MILLISECONDS = HOUR_MILLISECONDS * 24; | |
function toRelativeTime(date: string): string { | |
const rtf = new Intl.RelativeTimeFormat(lang, { numeric: "auto" }); | |
const creation = new Date(date).getTime(); | |
const now = new Date().getTime(); | |
let daysDifference = Math.round((creation - now) / DAY_MILLISECONDS); | |
let unit = "day"; | |
if (!daysDifference) { | |
daysDifference = Math.round((creation - now) / HOUR_MILLISECONDS); | |
unit = "hour"; | |
} | |
if (!daysDifference) { | |
daysDifference = Math.round((creation - now) / MINUTE_MILLISECONDS); | |
unit = "minute"; | |
} | |
//@ts-ignore | |
return rtf.format(daysDifference, unit); // ts doesn't know this unit is a Intl.RelativeTimeFormatUnit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment