5

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

3
  • 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) Commented Apr 14, 2018 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. Commented Apr 14, 2018 at 12:37
  • use new Date().toString() or some like, see, e.g stackoverflow.com/questions/1056728/… Commented Apr 14, 2018 at 13:38

2 Answers 2

8

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)),
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can find the official docs here. Output from the console:

The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".

I used DatePipe for this, but you could go with formatDate also (see here for more).

In your component:

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

constructor(
    private datePipe: DatePipe
)

ngOnInit() {
    this.dateControl.setValue(this.datePipe.transform(this.defaultValues, 'yyyy-MM-ddTHH:mm:ss'));
}

In your module declarations (e.g. app.module.ts) add DatePipe:

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

@NgModule({
    declarations: [
        AppComponent,
        // ...
    ],
    imports: [
        // ...

    ],
    providers: [
        DatePipe,
        // ...
    ],
    exports: // ...
    bootstrap: [AppComponent]
})
export class AppModule { }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.