Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input type date dont show value

Tags:

html

angular

I have a form control that gets a date but the input doesn't show the value

<input formControlName="startDate" name="startDate" type="date" class="form-control">

I determine the value through a patchValue I tried to use [value] but doesn't work I tried to convert to new Date() and it didn't work

this.form.patchValue({

  startDate: data.start,

});
like image 874
user3140824 Avatar asked May 31 '26 01:05

user3140824


1 Answers

Input type date accepts dates of the format yyyy-mm-dd. This means you will need to convert your dates to that format. You can convert it to an ISO date string first and then extract the date part of it but this, however, will not consider the timezone. So instead we will create a function that gets a date in the desired format while taking timezones into consideration. We can use getDate and getMonth as they consider the timezone.

formatDate(date: Date | string): string {
    date = new Date(date);
    const day = `${date.getDate() < 10 ? '0' : ''}${date.getDate()}`;
    const month = `${date.getMonth() + 1 < 10 ? '0' : ''}${date.getMonth() + 1}`;
    const year = date.getFullYear();
    return `${year}-${month}-${day}`;
}

Then just call this function to convert the format.

this.form.patchValue({
    startDate: this.formatDate(data.start)
});

You can also do this when you create the form. Note that even when you select a date from the input, it will bind in the same format yyyy-mm-dd.

like image 155
nash11 Avatar answered Jun 01 '26 14:06

nash11