Format Date Using Pipe | Angular


Format Date Using Pipe in Angular.

First you need to import DatePipe module file and add it to the providers array in your app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DatePipe } from '@angular/common';


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

Create an instance of DatePipe in your component file.

public currentDate: any;

constructor(private datePipe : DatePipe){}

ngOnInit(){
  this.currentDate = new Date();
}

Format Date as dd/MM/yyyy

To Format date as dd/MM/yyyy using pipes add the following code to app.component.html file.

<span>
    {{currentDate | date: 'dd/MM/yyyy'}}
</span>

Outputs : 10/07/2021

Format Date as dd-MMM-yyyy

<span>
    {{currentDate | date: 'dd-MMM-yyyy'}}
</span>

Outputs : 10-Jul-2021

Format Date as yyyy-MM-dd

<span>
    {{currentDate | date: 'yyyy-MM-dd'}}
</span>

Outputs : 2021-07-10

Format Date as yyyy-MM-dd hh:mm:ss

<span>
    {{currentDate | date: 'yyyy-MM-dd hh:mm:ss'}}
</span>

Outputs : 2021-07-10 09:39:12