Skip to content

Instantly share code, notes, and snippets.

@gocs
Last active January 29, 2025 09:11
Show Gist options
  • 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

ISO 8601 to local and relative datetime (moment.js alt)

image

function convertUTC0ToUTC8(timestamp: number) {
// Convert Unix timestamp (UTC+0) to milliseconds
const dateUTC0 = new Date(timestamp * 1000);
// Add 8 hours (UTC+8) in milliseconds
const dateUTC8 = new Date(dateUTC0.getTime() + 8 * 60 * 60 * 1000);
// // Format as RFC 3339 (YYYY-MM-DDTHH:mm:ss+08:00)
// return dateUTC8.toISOString().replace("Z", "+08:00");
return dateUTC8.toISOString();
}
<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 SECOND_MS = 1000;
const MINUTE_MS = SECOND_MS * 60;
const HOUR_MS = MINUTE_MS * 60;
const DAY_MS = HOUR_MS * 24;
const WEEK_MS = DAY_MS * 7;
const MONTH_MS = DAY_MS * 30;
const YEAR_MS = DAY_MS * 365;
const fmt = {
"year": YEAR_MS,
"month": MONTH_MS,
"week": WEEK_MS,
"day": DAY_MS,
"hour": HOUR_MS,
"minute": MINUTE_MS,
"second": SECOND_MS,
}
function toRelativeTime(date) {
const rtf = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });
const creation = new Date(date).getTime();
const now = new Date().getTime();
let odiff = creation - now
let diff
let unit
for (const [u, ms] of Object.entries(fmt)) {
unit = u
diff = Math.ceil(odiff / ms)
if (diff) break;
}
return rtf.format(diff, unit);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment