Search code examples
angularionic2

How to convert date into this 'yyyy-MM-dd' format in angular 2


I want to convert current date into 'yyyy-MM-dd' format in .ts file. In template it can easily be done by using date pipe. How to do that in typescript?

In template:

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

How to convert in this format 'yyyy-MM-dd' in typescript?

I am just getting current date by using this.

this.date =  new Date();

but I need to convert it into the given format.


Solution

  • The date can be converted in typescript to this format 'yyyy-MM-dd' by using Datepipe

    import { DatePipe } from '@angular/common'
    ...
    constructor(public datepipe: DatePipe){}
    ...
    myFunction(){
     this.date=new Date();
     let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
    }
    

    and just add Datepipe in 'providers' array of app.module.ts. Like this:

    import { DatePipe } from '@angular/common'
    ...
    providers: [DatePipe]