aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/shared-main/angular/from-now.pipe.ts
blob: dc6a25e83f55c32cf7fb343ba8928d7563fbbdb7 (plain) (blame)
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
import { Pipe, PipeTransform } from '@angular/core'
import { prepareIcu } from '@app/helpers'

// Thanks: https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
@Pipe({ name: 'myFromNow' })
export class FromNowPipe implements PipeTransform {
  private yearICU = prepareIcu($localize`{interval, plural, =1 {1 year ago} other {{interval} years ago}}`)
  private monthICU = prepareIcu($localize`{interval, plural, =1 {1 month ago} other {{interval} months ago}}`)
  private weekICU = prepareIcu($localize`{interval, plural, =1 {1 week ago} other {{interval} weeks ago}}`)
  private dayICU = prepareIcu($localize`{interval, plural, =1 {1 day ago} other {{interval} days ago}}`)
  private hourICU = prepareIcu($localize`{interval, plural, =1 {1 hour ago} other {{interval} hours ago}}`)

  transform (arg: number | Date | string) {
    const argDate = new Date(arg)
    const seconds = Math.floor((Date.now() - argDate.getTime()) / 1000)

    let interval = Math.floor(seconds / 31536000)
    if (interval >= 1) {
      return this.yearICU({ interval }, $localize`${interval} year(s) ago`)
    }

    interval = Math.floor(seconds / 2419200)
    // 12 months = 360 days, but a year ~ 365 days
    // Display "1 year ago" rather than "12 months ago"
    if (interval >= 12) return $localize`1 year ago`

    if (interval >= 1) {
      return this.monthICU({ interval }, $localize`${interval} month(s) ago`)
    }

    interval = Math.floor(seconds / 604800)
    // 4 weeks ~ 28 days, but our month is 30 days
    // Display "1 month ago" rather than "4 weeks ago"
    if (interval >= 4) return $localize`1 month ago`

    if (interval >= 1) {
      return this.weekICU({ interval }, $localize`${interval} week(s) ago`)
    }

    interval = Math.floor(seconds / 86400)
    if (interval >= 1) {
      return this.dayICU({ interval }, $localize`${interval} day(s) ago`)
    }

    interval = Math.floor(seconds / 3600)
    if (interval >= 1) {
      return this.hourICU({ interval }, $localize`${interval} hour(s) ago`)
    }

    interval = Math.floor(seconds / 60)
    if (interval >= 1) return $localize`${interval} min ago`

    return $localize`just now`
  }
}