Fix #6: Display relative timestamps

This commit is contained in:
2023-04-07 13:27:34 +02:00
parent 6267972605
commit a484810d2f
3 changed files with 58 additions and 4 deletions

40
src/lib/relativeTime.ts Normal file
View File

@ -0,0 +1,40 @@
import { derived, readable, type Readable } from 'svelte/store';
export const time = readable(new Date(), function start(set) {
const interval = setInterval(() => {
set(new Date());
}, 10000); //Every 10sec is enough, we don't need that much granularity
return function stop() {
clearInterval(interval);
};
});
export function secondsSince(date: Date): Readable<number> {
return derived(
time,
$time => Math.round(($time.getTime() - date.getTime()) / 1000)
);
}
export function relativeTime(seconds: number): string | null {
const min = 60;
if (seconds < min) {
return 'just now';
}
const hour = 60 * min;
if (seconds < hour) {
return `${Math.floor(seconds / min)}min`;
}
const day = hour * 24;
if (seconds < day) {
return `${(Math.floor(seconds / hour))}h`;
}
const maxRelative = day * 31;
if (seconds < maxRelative) {
return `${seconds % day}d`;
}
return null;
}