]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/angular/from-now.pipe.ts
Support ICU in TS components
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / angular / from-now.pipe.ts
1 import { Pipe, PipeTransform } from '@angular/core'
2 import { prepareIcu } from '@app/helpers'
3
4 // Thanks: https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
5 @Pipe({ name: 'myFromNow' })
6 export class FromNowPipe implements PipeTransform {
7 private yearICU = prepareIcu($localize`{interval, plural, =1 {1 year ago} other {{interval} years ago}}`)
8 private monthICU = prepareIcu($localize`{interval, plural, =1 {1 month ago} other {{interval} months ago}}`)
9 private weekICU = prepareIcu($localize`{interval, plural, =1 {1 week ago} other {{interval} weeks ago}}`)
10 private dayICU = prepareIcu($localize`{interval, plural, =1 {1 day ago} other {{interval} days ago}}`)
11 private hourICU = prepareIcu($localize`{interval, plural, =1 {1 hour ago} other {{interval} hours ago}}`)
12
13 transform (arg: number | Date | string) {
14 const argDate = new Date(arg)
15 const seconds = Math.floor((Date.now() - argDate.getTime()) / 1000)
16
17 let interval = Math.floor(seconds / 31536000)
18 if (interval >= 1) {
19 return this.yearICU({ interval }, $localize`${interval} year(s) ago`)
20 }
21
22 interval = Math.floor(seconds / 2419200)
23 // 12 months = 360 days, but a year ~ 365 days
24 // Display "1 year ago" rather than "12 months ago"
25 if (interval >= 12) return $localize`1 year ago`
26
27 if (interval >= 1) {
28 return this.monthICU({ interval }, $localize`${interval} month(s) ago`)
29 }
30
31 interval = Math.floor(seconds / 604800)
32 // 4 weeks ~ 28 days, but our month is 30 days
33 // Display "1 month ago" rather than "4 weeks ago"
34 if (interval >= 4) return $localize`1 month ago`
35
36 if (interval >= 1) {
37 return this.weekICU({ interval }, $localize`${interval} week(s) ago`)
38 }
39
40 interval = Math.floor(seconds / 86400)
41 if (interval >= 1) {
42 return this.dayICU({ interval }, $localize`${interval} day(s) ago`)
43 }
44
45 interval = Math.floor(seconds / 3600)
46 if (interval >= 1) {
47 return this.hourICU({ interval }, $localize`${interval} hour(s) ago`)
48 }
49
50 interval = Math.floor(seconds / 60)
51 if (interval >= 1) return $localize`${interval} min ago`
52
53 return $localize`just now`
54 }
55 }