]>
Commit | Line | Data |
---|---|---|
1 | import { Pipe, PipeTransform } from '@angular/core' | |
2 | ||
3 | // Thanks: https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site | |
4 | @Pipe({ name: 'myFromNow' }) | |
5 | export class FromNowPipe implements PipeTransform { | |
6 | transform (arg: number | Date | string) { | |
7 | const argDate = new Date(arg) | |
8 | const seconds = Math.floor((Date.now() - argDate.getTime()) / 1000) | |
9 | ||
10 | let interval = Math.floor(seconds / 31536000) | |
11 | if (interval > 1) return $localize`${interval} years ago` | |
12 | if (interval === 1) return $localize`1 year ago` | |
13 | ||
14 | interval = Math.floor(seconds / 2419200) | |
15 | // 12 months = 360 days, but a year ~ 365 days | |
16 | // Display "1 year ago" rather than "12 months ago" | |
17 | if (interval >= 12) return $localize`1 year ago` | |
18 | if (interval > 1) return $localize`${interval} months ago` | |
19 | if (interval === 1) return $localize`1 month ago` | |
20 | ||
21 | interval = Math.floor(seconds / 604800) | |
22 | // 4 weeks ~ 28 days, but our month is 30 days | |
23 | // Display "1 month ago" rather than "4 weeks ago" | |
24 | if (interval >= 4) return $localize`1 month ago` | |
25 | if (interval > 1) return $localize`${interval} weeks ago` | |
26 | if (interval === 1) return $localize`1 week ago` | |
27 | ||
28 | interval = Math.floor(seconds / 86400) | |
29 | if (interval > 1) return $localize`${interval} days ago` | |
30 | if (interval === 1) return $localize`1 day ago` | |
31 | ||
32 | interval = Math.floor(seconds / 3600) | |
33 | if (interval > 1) return $localize`${interval} hours ago` | |
34 | if (interval === 1) return $localize`1 hour ago` | |
35 | ||
36 | interval = Math.floor(seconds / 60) | |
37 | if (interval >= 1) return $localize`${interval} min ago` | |
38 | ||
39 | return $localize`just now` | |
40 | } | |
41 | } |