forked from AndrewPoyntz/time-ago-pipe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time-ago.pipe.ts
77 lines (77 loc) · 2.16 KB
/
time-ago.pipe.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
import {Pipe, PipeTransform, NgZone, ChangeDetectorRef, OnDestroy} from "@angular/core";
@Pipe({
name:'timeAgo',
pure:false
})
export class TimeAgoPipe implements PipeTransform, OnDestroy {
private timer: number;
constructor(private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone) {}
transform(value:string) {
this.removeTimer();
let d = new Date(value);
let now = new Date();
let seconds = Math.round(Math.abs((now.getTime() - d.getTime())/1000));
let timeToUpdate = (Number.isNaN(seconds)) ? 1000 : this.getSecondsUntilUpdate(seconds) *1000;
this.timer = this.ngZone.runOutsideAngular(() => {
if (typeof window !== 'undefined') {
return window.setTimeout(() => {
this.ngZone.run(() => this.changeDetectorRef.markForCheck());
}, timeToUpdate);
}
return null;
});
let minutes = Math.round(Math.abs(seconds / 60));
let hours = Math.round(Math.abs(minutes / 60));
let days = Math.round(Math.abs(hours / 24));
let months = Math.round(Math.abs(days/30.416));
let years = Math.round(Math.abs(days/365));
if (Number.isNaN(seconds)){
return '';
} else if (seconds <= 45) {
return '1m';
} else if (seconds <= 90) {
return '1m';
} else if (minutes <= 45) {
return minutes + 'm';
} else if (minutes <= 90) {
return '1h';
} else if (hours <= 22) {
return hours + 'h';
} else if (hours <= 36) {
return '1d';
} else if (days <= 25) {
return days + 'd';
} else if (days <= 45) {
return '1M';
} else if (days <= 345) {
return months + 'M';
} else if (days <= 545) {
return '1j';
} else { // (days > 545)
return years + 'j';
}
}
ngOnDestroy(): void {
this.removeTimer();
}
private removeTimer() {
if (this.timer) {
window.clearTimeout(this.timer);
this.timer = null;
}
}
private getSecondsUntilUpdate(seconds:number) {
let min = 60;
let hr = min * 60;
let day = hr * 24;
if (seconds < min) { // less than 1 min, update every 2 secs
return 2;
} else if (seconds < hr) { // less than an hour, update every 30 secs
return 30;
} else if (seconds < day) { // less then a day, update every 5 mins
return 300;
} else { // update every hour
return 3600;
}
}
}