48 lines
2.0 KiB
TypeScript
48 lines
2.0 KiB
TypeScript
import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core';
|
|
import * as moment from 'moment';
|
|
import { TranslateService } from '@ngx-translate/core';
|
|
import { DatePipe as BaseDatePipe } from '@angular/common';
|
|
|
|
const HOURS_IN_A_DAY = 24;
|
|
const MINUTES_IN_AN_HOUR = 60;
|
|
|
|
@Pipe({
|
|
name: 'date'
|
|
})
|
|
export class DatePipe extends BaseDatePipe implements PipeTransform {
|
|
constructor(@Inject(LOCALE_ID) private readonly _locale: string, private readonly _translateService: TranslateService) {
|
|
super(_locale);
|
|
}
|
|
|
|
transform(value: null | undefined, format?: string, timezone?: string, locale?: string): null;
|
|
transform(value: Date | string | number | null | undefined, format?: string, timezone?: string, locale?: string): string | null;
|
|
transform(value: any, format?: string, timezone?: string, locale?: string): string {
|
|
if (format === 'timeFromNow') return this._getTimeFromNow(value);
|
|
return super.transform(value, format, timezone, locale);
|
|
}
|
|
|
|
private _getTimeFromNow(item: string) {
|
|
const date = moment(item);
|
|
const now = new Date(Date.now());
|
|
|
|
const daysLeft = date.diff(now, 'days');
|
|
const hoursFromNow = date.diff(now, 'hours');
|
|
const hoursLeft = hoursFromNow - HOURS_IN_A_DAY * daysLeft;
|
|
const minutesFromNow = date.diff(now, 'minutes');
|
|
const minutesLeft = minutesFromNow - HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * daysLeft;
|
|
|
|
if (daysLeft === 0 && hoursLeft === 0 && minutesLeft > 0) return this._translateService.instant('time.less-than-an-hour');
|
|
|
|
const hoursDisplay = this._translateService.instant('time.hours', { hours: hoursLeft });
|
|
|
|
if (daysLeft === 0 && hoursLeft > 0) return hoursDisplay;
|
|
|
|
const daysDisplay = this._translateService.instant('time.days', { days: daysLeft });
|
|
|
|
if (daysLeft > 0 && hoursLeft > 0) return `${daysDisplay} ${hoursDisplay}`;
|
|
if (daysLeft > 0) return daysDisplay;
|
|
|
|
return this._translateService.instant(`time.no-time-left`);
|
|
}
|
|
}
|