Angular2 - Setting date field on reactive form

When you run this code in Chrome (other browsers not tested) it logs an error to console:

The specified value "7/26/2017" does not conform to the required format, "yyyy-MM-dd".

Which I think describes the problem pretty well

You can fix it by changing your currentDate() method to something like:

currentDate() {
  const currentDate = new Date();
  return currentDate.toISOString().substring(0,10);
}

Live plunker example

While this does fix the problem the answer from @JGFMK shows a better way of converting the date using a DatePipe


FormBuilder.group returns FormGroup:
https://angular.io/api/forms/FormBuilder#group
https://angular.io/api/forms/FormGroup#setValue

Updates:

  • Using Angular Pipe in Typescript is discussed here.
  • Discussion for locale: navigator.language.
  • Instantiate a Date Pipe
  • Discussion on Dates in Angular.
  • Date Pipe docs and source code.

import {DatePipe} from '@angular/common'
...
let dp = new DatePipe(navigator.language);
let p = 'y-MM-dd'; // YYYY-MM-DD
let dtr = dp.transform(new Date(), p);
this.transitionForm.setValue({effectiveEndDate: dtr}); 

Plunker example (just hit reset)