Date format change angular 2

Jędrek Markowski picture Jędrek Markowski · Jun 30, 2017 · Viewed 41.9k times · Source

I need to change my date format, the problem is that I can't use moment.js, I need just to transform date from yyyy-mm-dd to dd-mm-yyyy. I use angular v 2.4.0.

Answer

Yordan Nikolov picture Yordan Nikolov · Jun 30, 2017

Use DatePipe pipe

date_expression | date[:format]

in your case

{{ date_expression | date:'dd-MM-yy' }}

How to use the pipe inside the component :

NgModule({
  ....
  providers: [DatePipe]
})

or

@Component({
   ....
  providers: [DatePipe]
})

In you component set it as a date variable

constructor(private datePipe: DatePipe) {
}

ngOnInit() {
    this.date = this.datePipe.transform(new Date(), 'dd-MM-yy');
}