Saturday, June 23, 2018

Format Dates with a Custom Date Pipe in Angular 2 +

Angular 2 DatePipe provides different sets of formats to display in a browser. Angular DatePipe comes with @angular/common. The date input can be given as date object, milliseconds or an ISO date string.

DatePipe is a Pipe API that works using pipe operator ( | ). Accordingly, you can place date expression on the left side of the pipe, and on the right side with required date formats based on as
{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}
given in the official documentation.

By default, most of the predefined formats support the American date format (month/day/year). But, If you like to go with default formatting as giving in the documentation, you can use

Date : {{currentDate | date }}

Date : {{currentDate | date: 'MMM-dd-yyyy' }}

Date : {{currentDate | date: 'MM-dd-yyyy' }}

Date : {{currentDate | date: 'yMMMdjms' }}

Date : {{currentDate | date: 'yMMMMEEEEd' }}

As a good programming practice, it is always recommended to
wrap default pipe in your application. Assume, you have defined the date to be displayed as 'short' with default formatting throughout the application which angular has provided.

In case if the client asks to update the date format throughout the application the only way is to find and replace date format in the entire application which is not going to be a scalable solution in long-term.

Let's create a custom dateFormat pipe to cater this issue to configure your dateFormat in a single place.

Step 01: Create an Angular App
  $ ng new dateFormatApp

Step 02: Navigate to your dateFormatApp
  $ cd dateFormatApp

Step 03: Create a Pipe using Angular CLI
  $ ng g pipe DateFormat

So, date-format.pipe.ts looks like this:
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
  name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {

  private readonly dateFormat = "dd-MM-yyyy"; // feel free to move this to a constants.ts file
  transform(value: any, args?: any): any {
    return super.transform(value, this.dateFormat);
  }
}
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Custome DateFormat Pipe Demo';
  date = new Date();
}
app.component.html
Welcome to {{ title }}!
Date: {{date | dateFormat}}

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { DateFormatPipe } from './pipes/date-format.pipe';

@NgModule({
  declarations: [AppComponent, DateFormatPipe],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Output


4 comments: