|
| 1 | +import { Pipe, PipeTransform } from '@angular/core'; |
| 2 | +import { TranslateService } from '@ngx-translate/core'; |
| 3 | + |
| 4 | +import { |
| 5 | + differenceInYears, |
| 6 | + differenceInMonths, |
| 7 | + differenceInWeeks, |
| 8 | + differenceInDays, |
| 9 | + differenceInHours, |
| 10 | + differenceInMinutes |
| 11 | +} from 'date-fns'; |
| 12 | + |
| 13 | + |
| 14 | +@Pipe({ |
| 15 | + name: 'readableDate' |
| 16 | +}) |
| 17 | +export class ReadableDatePipe implements PipeTransform { |
| 18 | + constructor (private translate: TranslateService) {} |
| 19 | + |
| 20 | + transform(date: Date, ...args: unknown[]): Promise<string> { |
| 21 | + const now = new Date(); |
| 22 | + |
| 23 | + const years = differenceInYears(now, date); |
| 24 | + if(years > 0) { |
| 25 | + return this.translate.get(years>1 ? 'readableDate.yearsAgo' : 'readableDate.yearAgo').toPromise() |
| 26 | + .then(_ => { return years + ' ' + _; }); |
| 27 | + } |
| 28 | + |
| 29 | + const months = differenceInMonths(now, date); |
| 30 | + if(months > 0) { |
| 31 | + return this.translate.get(months> 1 ? 'readableDate.monthsAgo' : 'readableDate.monthAgo').toPromise() |
| 32 | + .then(_ => { return months + ' ' + _; }); |
| 33 | + } |
| 34 | + |
| 35 | + const weeks = differenceInWeeks(now, date); |
| 36 | + if(weeks > 0) { |
| 37 | + return this.translate.get(weeks>1 ? 'readableDate.weeksAgo' : 'readableDate.weekAgo').toPromise() |
| 38 | + .then(_ => { return weeks + ' ' + _; }); |
| 39 | + } |
| 40 | + |
| 41 | + const days = differenceInDays(now, date); |
| 42 | + if(days > 0) { |
| 43 | + return this.translate.get(days>1 ? 'readableDate.daysAgo' : 'readableDate.dayAgo').toPromise() |
| 44 | + .then(_ => { return days + ' ' + _; }); |
| 45 | + } |
| 46 | + |
| 47 | + const hours = differenceInHours(now, date); |
| 48 | + if(hours > 0) { |
| 49 | + return this.translate.get(hours>1 ? 'readableDate.hoursAgo' : 'readableDate.hourAgo').toPromise() |
| 50 | + .then(_ => { return hours + ' ' + _; }); |
| 51 | + } |
| 52 | + |
| 53 | + const minutes = differenceInMinutes(now, date); |
| 54 | + return this.translate.get(minutes>1 ? 'readableDate.minutesAgo' : 'readableDate.minuteAgo').toPromise() |
| 55 | + .then(_ => { return minutes + ' ' + _; }); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments