Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind date/time form control?

Here is my simple code that works only for 'title'. 'docdatetime' control appears blank. What am I doing wrong?

//template ===================================================
<div class="form-group">
  <input type="text" id="title" formControlName="title" class="form-control">
</div>

<div class="form-group">
  <input type="datetime-local" id="docdatetime" formControlName="docdatetime" class="form-control">
</div>

//component.ts ===============================================
import { FormGroup, FormControl } from '@angular/forms';
..... 

export class..... 
    docForm: FormGroup;

    ngOnInit() {
        let docTitle = 'My first document';
        let docDate = 'Jun 15, 2015, 9:43:11 PM';
        this.docForm = new FormGroup({
            'title': new FormControl(docTitle),
            'docdatetime': new FormControl(new Date(docDate))
        });
    }   

enter image description here

like image 399
VladP Avatar asked Oct 12 '17 17:10

VladP


1 Answers

The reason for this error is that the DatetimeLocal property on the input requires a very specific format, being YYYY-MM-DDTHH:MM:SS.SSS. This format is known as an ISO Date. So to fix your error, you have to pass in a date in that format. HOWEVER, an actual ISO Date's format is YYYY-MM-DDTHH:MM:SS.SSSZ. The Z refers to the timezone, which is always zero UTC offset. Look here for information on ToISOString(). So, an easy fix for that is to simply slice off the last character, which will always be the character Z in the new Date().toISOString().

let docTitle = 'My first document';
let docDate = 'Jun 15, 2015, 21:43:11 UTC'; //You'll want to change this to UTC or it can mess up your date.
this.docForm = new FormGroup({
    'title': new FormControl(docTitle),
    'docdatetime': new FormControl(new Date(docDate).toISOString().slice(0, -1))
});

NOTE

This means that the value you receive from that input will NOT be an actual Date. It'll be a string. So if you need it to be a date later on, make sure you create a New Date() using the value of the string and you should be good to go.

like image 194
Jun Kang Avatar answered Oct 17 '22 02:10

Jun Kang