Skip to content

Instantly share code, notes, and snippets.

@gocs
Last active March 11, 2024 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gocs/9d4b23d72193aca646ff58ff8e0b3158 to your computer and use it in GitHub Desktop.
Save gocs/9d4b23d72193aca646ff58ff8e0b3158 to your computer and use it in GitHub Desktop.
ISO 8601 to local and relative datetime plus svelte ticker component
<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>
function toAutoLocalDate(date: string): string {
return Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale).format(new Date(date));
}
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