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

Umar Rasheed picture Umar Rasheed · Nov 2, 2016 · Viewed 193.9k times · Source

I want to convert current data into 'yyyy-MM-dd' format in .ts file. i template it can easily be done by using data 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.

now i am just getting current date by using this.

this.date =  new Date();

but need to convert it into given format. Please guide how to do that... Thanks!

Answer

Umar Rasheed picture Umar Rasheed · Nov 7, 2016

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]