aboutsummaryrefslogtreecommitdiff
path: root/src/components/timeago/timeago.vue
blob: bed290202a7a5dea09eb58d5caa3daa52b0bd7da (plain)
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
<template>
  <time
    :datetime="time"
    :title="localeDateString"
  >
    {{ $t(relativeTime.key, [relativeTime.num]) }}
  </time>
</template>

<script>
import * as DateUtils from 'src/services/date_utils/date_utils.js'
import localeService from 'src/services/locale/locale.service.js'

export default {
  name: 'Timeago',
  props: ['time', 'autoUpdate', 'longFormat', 'nowThreshold'],
  data () {
    return {
      relativeTime: { key: 'time.now', num: 0 },
      interval: null
    }
  },
  computed: {
    localeDateString () {
      const browserLocale = localeService.internalToBrowserLocale(this.$i18n.locale)
      return typeof this.time === 'string'
        ? new Date(Date.parse(this.time)).toLocaleString(browserLocale)
        : this.time.toLocaleString(browserLocale)
    }
  },
  created () {
    this.refreshRelativeTimeObject()
  },
  unmounted () {
    clearTimeout(this.interval)
  },
  methods: {
    refreshRelativeTimeObject () {
      const nowThreshold = typeof this.nowThreshold === 'number' ? this.nowThreshold : 1
      this.relativeTime = this.longFormat
        ? DateUtils.relativeTime(this.time, nowThreshold)
        : DateUtils.relativeTimeShort(this.time, nowThreshold)

      if (this.autoUpdate) {
        this.interval = setTimeout(
          this.refreshRelativeTimeObject,
          1000 * this.autoUpdate
        )
      }
    }
  }
}
</script>