3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 8

Days Ago Pipe

Creating a custom pipe to display dates nicely

STANDARD

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 {}
STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).