1 import { convertTimestampToMilliseconds } from './convertTimestampToMilliseconds'
3 function createFormatter(languageCode: Intl.LocalesArgument) {
4 return new Intl.RelativeTimeFormat(languageCode, {
5 localeMatcher: 'best fit',
11 let rtf = createFormatter('en')
12 let lastUsedRtfLanguage: Intl.LocalesArgument = 'en'
14 export class ServerTime {
15 constructor(public serverTimestamp: number) {}
17 get milliseconds(): number {
18 return convertTimestampToMilliseconds(this.serverTimestamp)
22 return new Date(this.milliseconds)
25 get relativeSeconds(): number {
26 return Math.round((this.milliseconds - Date.now()) / 1000)
29 get relativeMinutes(): number {
30 return Math.round(this.relativeSeconds / 60)
33 isNewerThan(number: number, type: 'seconds' | 'minutes') {
34 if (type === 'seconds') {
35 return this.relativeSeconds > -number
36 } else if (type === 'minutes') {
37 return this.relativeMinutes > -number
41 relativeFormat(time: number, unit: Intl.RelativeTimeFormatUnit, languageCode: Intl.LocalesArgument) {
42 if (lastUsedRtfLanguage !== languageCode) {
44 rtf = createFormatter(languageCode)
45 lastUsedRtfLanguage = languageCode
47 rtf = createFormatter('en')
48 lastUsedRtfLanguage = 'en'
52 return rtf.format(time, unit)
55 static now(): ServerTime {
56 return new ServerTime(Math.round(Date.now() / 1000))