Menu

Angular 2 using DatePipe to format date on TypeScript

in your app.module.ts file you need to import the DatePipe module

import { DatePipe } from '@angular/common';

then under providers you need to include the DatePipe

providers: [
DatePipe, 
.......

In your component import it again

import { DatePipe } from '@angular/common';

Use dependency injection so it available to component

constructor(public fb: FormBuilder, public datepipe: DatePipe) {

}

this is how you actualy use it to format your date

ngOnInit() {
this.form = this.initForm();

var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

let from = this.datepipe.transform(yesterday, 'yyyy-MM-dd');
let to = this.datepipe.transform(new Date(), 'yyyy-MM-dd');
this.form.patchValue({
searchDateFrom: from,
searchDateTo: to,
});
.....
}

In my case I actually had to populate the form controls.

Leave a comment