-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDateFormat.ts
80 lines (68 loc) · 2.68 KB
/
DateFormat.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict'
export default class {
public static toDateTimeIso(date: Date): string {
return `${date.getFullYear()}-${this.pad(date.getMonth() + 1)}-${this.pad(date.getDate())} ${
this.pad(date.getHours())}:${this.pad(date.getMinutes())}:${this.pad(date.getSeconds())} ${
this.getOffset(date)}`
}
public static toDateIso(date: Date): string {
return `${date.getFullYear()}-${this.pad(date.getMonth() + 1)}-${this.pad(date.getDate())}`
}
public static toFullyReadable(date: Date): string {
return `${new Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale, {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}).format(date)} ${this.getOffset(date)}`
}
public static toDateTimeSmall(date: Date): string {
return new Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale, {
year: '2-digit',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: false,
}).format(date)
}
public static toDateSmall(date: Date): string {
return new Intl.DateTimeFormat(Intl.DateTimeFormat().resolvedOptions().locale, {
year: '2-digit',
month: 'short',
day: 'numeric',
}).format(date)
}
public static ago(date: Date): string {
const units = {
year: 31536000,
month: 2630016,
day: 86400,
hour: 3600,
minute: 60,
second: 1,
}
const { value, unit } = ((date: Date) => {
const secondsElapsed = (Date.now() - date.getTime()) / 1000
for (const [unit, secondsInUnit] of Object.entries(units)) {
if (secondsElapsed >= secondsInUnit || unit === 'second') {
return { value: Math.floor(secondsElapsed / secondsInUnit) * -1, unit }
}
}
})(date)
return (new Intl.RelativeTimeFormat()).format(value, unit as Intl.RelativeTimeFormatUnit)
}
private static getOffset(date: Date): string {
const offset = date.getTimezoneOffset()
const hrs = `0${Math.floor(Math.abs(offset) / 60)}`.slice(-2)
const mins = `0${Math.abs(offset) % 60}`.slice(-2)
const readableOffset = `${hrs}${mins}`
return offset > 0 ? `-${readableOffset}` : readableOffset
}
private static pad(n: number): string {
return n < 10 ? `0${n}` : `${n}`
}
}