I am working on an Angular application (v4.4.3) with Angular Material Beta 11 version. With beta 11, the datepicker is accepting date in ISOformat string. However, in my app the date in the date picker module is off by 1 day, as shown in below image:
The flow of date in my app is follows, the app receives a date in Unix Epoch time from Mysql database and I convert that Epoch time date into ISOString string format and return that ISO date to matDatePicker.
/**
* This method takes the key, which is a epoch time in string format and convert into JS Date object.
* @param key {string} - the epoch time
* @return {string} - Date Object.
*/
private static dateHelper(key: string): any {
const dateObj = new Date(+key * 1000);
// Need to return ISOString format date as accepted by Material DatePicker component
return dateObj.toISOString().substring(0, 10);
}
I also have Date Picker Module, to display the date in customized format:
import {NgModule} from '@angular/core';
import {MdDatepickerModule, MdNativeDateModule, NativeDateAdapter, DateAdapter, MD_DATE_FORMATS} from '@angular/material';
// extend NativeDateAdapter's format method to specify the date format.
export class CustomDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getUTCDate();
const month = date.getUTCMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
} else {
return date.toDateString();
}
}
}
const MY_DATE_FORMATS = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
@NgModule({
declarations: [],
imports: [],
exports: [MdDatepickerModule, MdNativeDateModule],
providers: [
{
provide: DateAdapter, useClass: CustomDateAdapter
},
{
provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS
}
]
})
export class DatePickerModule {
}
The DatePicker:
<mat-form-field>
<input matInput
[matDatepicker]="myDate"
placeholder="Start Date"
[(ngModel)]="date"
name="start_date" required>
<mat-datepicker-toggle matSuffix [for]="myDate"></mat-datepicker-toggle>
<mat-datepicker #myDate></mat-datepicker>
<mat-error>This field is required!</mat-error>
</mat-form-field>
I did Google about it and there were some posts with this issue but I was not able to follow them completely. Any input of this would be highly appreciated. Thanks!