aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/angular/from-now.pipe.ts
blob: 3a9a76411f17b44e807ec1c74374cee007989fb8 (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
import { Pipe, PipeTransform } from '@angular/core'
import { I18n } from '@ngx-translate/i18n-polyfill'

// 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 {

  constructor (private i18n: I18n) { }

  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.i18n('{{interval}} years ago', { interval })
    }

    interval = Math.floor(seconds / 2592000)
    if (interval > 1) return this.i18n('{{interval}} months ago', { interval })
    if (interval === 1) return this.i18n('{{interval}} month ago', { interval })

    interval = Math.floor(seconds / 604800)
    if (interval > 1) return this.i18n('{{interval}} weeks ago', { interval })
    if (interval === 1) return this.i18n('{{interval}} week ago', { interval })

    interval = Math.floor(seconds / 86400)
    if (interval > 1) return this.i18n('{{interval}} days ago', { interval })
    if (interval === 1) return this.i18n('{{interval}} day ago', { interval })

    interval = Math.floor(seconds / 3600)
    if (interval > 1) return this.i18n('{{interval}} hours ago', { interval })
    if (interval === 1) return this.i18n('{{interval}} hour ago', { interval })

    interval = Math.floor(seconds / 60)
    if (interval >= 1) return this.i18n('{{interval}} min ago', { interval })

    return this.i18n('{{interval}} sec ago', { interval: Math.max(0, seconds) })
  }
}