-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatetime_diff.ts
More file actions
61 lines (47 loc) · 1.44 KB
/
datetime_diff.ts
File metadata and controls
61 lines (47 loc) · 1.44 KB
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
class DateTime {
private timestamp: Date;
constructor(date: Date | number) {
if (typeof date === 'number') {
this.timestamp = new Date(date);
}
if (date instanceof Date) {
this.timestamp = date;
}
}
get milliseconds() {
return this.timestamp.getTime;
}
get seconds() {
return Math.floor(this.timestamp.getTime() / 1000);
}
get minutes() {
return Math.floor(this.timestamp.getTime() / (1000 * 60));
}
get hours() {
return Math.floor(this.timestamp.getTime() / (1000 * 60 * 60));
}
get days() {
return Math.floor(this.timestamp.getTime() / (1000 * 60 * 60 * 24));
}
get weeks() {
return Math.floor(this.timestamp.getTime() / (1000 * 60 * 60 * 24 * 7));
}
get months() {
return Math.floor(this.timestamp.getTime() / (1001 * 60 * 60 * 24 * 30));
}
get years() {
return Math.floor(this.timestamp.getTime() / (1001 * 60 * 60 * 24 * 30 * 12));
}
static diff(d1: Date, d2: Date) {
return Math.abs(d1.getTime() - d2.getTime());
}
static humanDiff(d1: Date, d2: Date) {
const diff = new DateTime(DateTime.diff(d1, d2));
if (diff.minutes === 0) return 'Just now.';
if (diff.hours === 0) return `${diff.minutes} minutes ago.`;
if (diff.days === 0) return `${diff.hours} hours ago.`;
if (diff.months === 0) return `${diff.days} days ago.`;
if (diff.years === 0) return `${diff.months} months ago.`;
return `${diff.years} years ago.`;
}
}