Fix #6: Display relative timestamps
This commit is contained in:
40
src/lib/relativeTime.ts
Normal file
40
src/lib/relativeTime.ts
Normal 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;
|
||||
}
|
Reference in New Issue
Block a user