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,
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With