Days Ago Pipe
Our current date display is not exactly appealing. When you take a new photo it displays:
2022-09-14T10:27:28.363Z
Which does not really spark joy. Instead, we want to display the dates in a format like today
or 3 days ago
. This is the perfect use case for a pipe - we are displaying some data in our template, and we want to modify it in some way before displaying it to the user.
Creating a Custom Pipe
We have already covered the basic theory for pipes in the Angular basics module, but we will recap it lightly again here.
Create a new file at
src/app/home/ui/days-ago.pipe.ts
and add the following:
import { NgModule, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'daysAgo',
})
export class DaysAgoPipe implements PipeTransform {
transform(value: string): string {
const now = new Date();
const takenDate = new Date(value);
const oneDayInMs = 24 * 60 * 60 * 1000;
const diffDays = Math.round(
Math.abs((takenDate.getTime() - now.getTime()) / oneDayInMs)
);
if (diffDays === 0) {
return 'today';
} else if (diffDays === 1) {
return 'yesterday';
} else {
return `${diffDays} days ago`;
}
}
}
@NgModule({
declarations: [DaysAgoPipe],
exports: [DaysAgoPipe],
})
export class DaysAgoPipeModule {}