]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | import { Pipe, PipeTransform } from '@angular/core'; |
2 | ||
f67539c2 TL |
3 | import _ from 'lodash'; |
4 | import moment from 'moment'; | |
5 | ||
6 | moment.updateLocale('en', { | |
7 | relativeTime: { | |
8 | future: $localize`in %s`, | |
9 | past: $localize`%s ago`, | |
10 | s: $localize`a few seconds`, | |
11 | ss: $localize`%d seconds`, | |
12 | m: $localize`a minute`, | |
13 | mm: $localize`%d minutes`, | |
14 | h: $localize`an hour`, | |
15 | hh: $localize`%d hours`, | |
16 | d: $localize`a day`, | |
17 | dd: $localize`%d days`, | |
18 | w: $localize`a week`, | |
19 | ww: $localize`%d weeks`, | |
20 | M: $localize`a month`, | |
21 | MM: $localize`%d months`, | |
22 | y: $localize`a year`, | |
23 | yy: $localize`%d years` | |
24 | } | |
25 | }); | |
11fdf7f2 TL |
26 | |
27 | @Pipe({ | |
f67539c2 TL |
28 | name: 'relativeDate', |
29 | pure: false | |
11fdf7f2 TL |
30 | }) |
31 | export class RelativeDatePipe implements PipeTransform { | |
f67539c2 TL |
32 | /** |
33 | * Convert a time into a human readable form, e.g. '2 minutes ago'. | |
34 | * @param {Date | string | number} value The date to convert, should be | |
35 | * an ISO8601 string, an Unix timestamp (seconds) or Date object. | |
36 | * @param {boolean} upperFirst Set to `true` to start the sentence | |
37 | * upper case. Defaults to `true`. | |
38 | * @return {string} The time in human readable form or an empty string | |
39 | * on failure (e.g. invalid input). | |
40 | */ | |
41 | transform(value: Date | string | number, upperFirst = true): string { | |
42 | let date: moment.Moment; | |
aee94f69 | 43 | const offset = moment().utcOffset(); |
f67539c2 | 44 | if (_.isNumber(value)) { |
aee94f69 | 45 | date = moment.parseZone(moment.unix(value)).utc().utcOffset(offset).local(); |
f67539c2 | 46 | } else { |
aee94f69 | 47 | date = moment.parseZone(value).utc().utcOffset(offset).local(); |
f67539c2 TL |
48 | } |
49 | if (!date.isValid()) { | |
50 | return ''; | |
51 | } | |
52 | let relativeDate: string = date.fromNow(); | |
53 | if (upperFirst) { | |
54 | relativeDate = _.upperFirst(relativeDate); | |
11fdf7f2 | 55 | } |
f67539c2 | 56 | return relativeDate; |
11fdf7f2 TL |
57 | } |
58 | } |