To address this issue, I took the initiative to create my own user-friendly Date Pipe. You can easily generate a Custom Date Pipe in the pipes folder by using the Angular CLI command ng g p pipes/DateAgo
.
Once you execute the command, the generated file structure will include two files. If testing is not a concern for you, feel free to delete the date-ago.pipe.spec.ts
file.
In the newly created date-ago.pipe.ts
file, simply insert the following code:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'dateAgo',
pure: true
})
export class DateAgoPipe implements PipeTransform {
transform(value: any, args?: any): any {
if (value) {
const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
if (seconds < 29)
return 'Just now';
const intervals = {
'year': 31536000,
'month': 2592000,
'week': 604800,
'day': 86400,
'hour': 3600,
'minute': 60,
'second': 1
};
let counter;
for (const i in intervals) {
counter = Math.floor(seconds / intervals[i]);
if (counter > 0)
if (counter === 1) {
return counter + ' ' + i + ' ago';
} else {
return counter + ' ' + i + 's ago';
}
}
}
return value;
}
}
Don't forget to import the Custom Date Pipe in your app.modules.ts
file and add it to the declarations: [...DateAgoPipe]
array. If you didn't use Angular CLI to generate the Date Pipe, ensure to perform this step manually.
Lastly, update the HTML code from
<p>Published: {{dog.date | date}}</p>
to
<p>Published: {{dog.date | dateAgo}}</p>
and witness the magic unfold.