- How to format DateTime with a Custom DateTime Pipe in Angular 2 +
- How to format Dates with a Custom Date Pipe in Angular 2 +
Step 01: Create an Angular App
$ ng new demoPipeApp
Step 02: Navigate to your dateFormatApp
$ cd demoPipeApp
Step 03: Create a file to store format options
constants.ts
export class Constants {
public static readonly dateFormat: string = "dd-MM-yyyy";
public static readonly dateTimeFormat: string = `${Constants.dateFormat} HH:mm`;
}
Step 04: Create a Module to register all the pipes using Angular CLI
$ ng g module DateTimeFormatPipes // this will creatte date-format-pipes.module.ts
Step 05: Create "DateTimeFormat" Pipe using Angular CLI
$ ng g pipe DateTimeFormat
date-time-format.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateTimeFormat'
})
export class DateTimeFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
return super.transform(value, this.dateTimeFormat);
}
}
Step 06: Create "DateFormat" Pipe using Angular CLI
$ ng g pipe DateFormat
date-format.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Constants } from '../modals/constants';
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
return super.transform(value, Constants.dateFormat);
}
}
Step 07: Declare and Export both pipes in "date-format-pipes.module.ts"
date-format.pipe.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DateFormatPipe } from './date-format.pipe';
import { DateTimeFormatPipe } from './date-time-format.pipe';
@NgModule({
imports: [
CommonModule
],
declarations: [DateFormatPipe, DateTimeFormatPipe],
exports: [DateFormatPipe, DateTimeFormatPipe]
})
export class DateFormatPipesModule { }
Step 08: Import "DateFormatPipesModule" to "app.module.ts"
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { DateFormatPipesModule } from './date-format-pipes/date-format-pipes.module';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, DateFormatPipesModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 09: Modify the "app.component.html"
Date: {{date | dateFormat}}
DateTime: {{date | dateTimeFormat}}
Output
No comments:
Post a Comment