I am trying to create a \'time ago\' pipe for my Angular 2 application.
It should transform a date to a string such as \'5 minutes ago\' or \'60 seconds ago\'. It wo
The accepted answer can not work with angular 7+.
I followed this answer and customize for Vietnamese.
https://stackoverflow.com/a/61341940/4964569
I share for whom concern.
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'dateAgo',
pure: true
})
export class TimePipe implements PipeTransform {
transform(value: any, args?: any): any {
if (value) {
const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
if (seconds < 29) // less than 30 seconds ago will show as 'Just now'
return 'vừa mới đăng';
const intervals = {
'năm': 31536000,
'tháng': 2592000,
'tuần': 604800,
'ngày': 86400,
'giờ': 3600,
'phút': 60,
'giây': 1
};
let counter;
for (const i in intervals) {
counter = Math.floor(seconds / intervals[i]);
if (counter > 0){
return counter + ' ' + i + ' trước'; // singular (1 day ago)
}
}
}
return value;
}
}