4

I am unable to assign value to `datetime-local element in a form.

Code from template:

Code from HTML template

Code from typescript file:

let dateTime : Date = new Date();

this.testForm = this.formBuilder.group({    
  'dateTime': new FormControl(dateTime),
});

Result:

enter image description here

What is the proper way to assign date & time to datetime-local using typescript

HDJEMAI
  • 8,842
  • 44
  • 66
  • 88
Robert Williams
  • 1,301
  • 1
  • 13
  • 33
  • type datetime-local is a "string" type, so you can do this.testForm = this.formBuilder.group({ 'dateTime': '2017-06-01T08:30', });. Anyway, I suggested NOT use type datetime-local. This don't work in all navigators (e.g. you see as "normal" input in FireFox) – Eliseo Apr 14 '18 at 12:28
  • @Eliseo Thanks for your suggestion. Hard coded string works perfectly but I want to assign system's current date and time to the datetime-local. – Robert Williams Apr 14 '18 at 12:37
  • use new Date().toString() or some like, see, e.g https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – Eliseo Apr 14 '18 at 13:38

1 Answers1

3

datetime-local requires value in specific format (yyyy-mm-ddThh:mm)

You can try the following,

const dateTime = new Date();
this.testForm = this.formBuilder.group({    
  dateTime: new FormControl(dateTime.toISOString().substring(0, 16)),
});
Yuvaraj V
  • 790
  • 2
  • 13
  • 26