63 lines
2.3 KiB
TypeScript
63 lines
2.3 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._translate('time.less-than-an-hour');
|
|
|
|
const hoursSuffix = this._translate(`time.hour${hoursLeft === 1 ? '' : 's'}`);
|
|
const hoursDisplay = `${hoursLeft} ${hoursSuffix}`;
|
|
|
|
if (daysLeft === 0 && hoursLeft > 0) return hoursDisplay;
|
|
|
|
const daysSuffix = this._translate(`time.day${daysLeft === 1 ? '' : 's'}`);
|
|
const daysDisplay = `${daysLeft} ${daysSuffix}`;
|
|
|
|
if (daysLeft > 0 && hoursLeft > 0) return `${daysDisplay} ${hoursDisplay}`;
|
|
if (daysLeft > 0) return daysDisplay;
|
|
|
|
return this._translate(`time.no-time-left`);
|
|
}
|
|
|
|
private _translate(value: string, params?: { [key: string]: string }) {
|
|
return this._translateService.instant(value, params);
|
|
}
|
|
}
|