Material Angular 6 DatePicker is parsing my date 1 day before
For anyone who just wants their dates to be UTC dates and is stuck using the JS Date object via DatePicker, you can just add an adapter option to the @NgModule
providers:
@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } }
]
})
You'll need add @angular/material-moment-adapter
to your package.json
and import the module/options object:
import {MAT_MOMENT_DATE_ADAPTER_OPTIONS, MatMomentDateModule} from '@angular/material-moment-adapter';
Once this is done, any DatePicker will provide UTC dates, and considering there's no opportunity to select a time component with DatePicker, this seems appropriate.
Pulled from the Material DatePicker info.
So, after a little bit of research I've find out that it was a timezone issue. To temporary fix it, I had to concatenate T00:00:00 to the end of my date that was coming from backend under the format yyyy/MM/dd.
The best option is, if it's possible, to the backend to change the format to yyyy/MM/ddTHH:mm:ss.
Otherwise there's 2 options to solve the problem when you have to use the format yyyy/MM/dd in your Angular 6 Material DatePicker: te bad and the good.
- The bad (and possible just a temporary) is to do what I did, concatenate T00:00:00 to the end of the date before the DatePicker parses it.
- The good is to actually get the date string, convert it into date, convert the timezone to GMT and then allow the DatePicker to parse it.
I hope I can help the desperate all over, like me.
You can do a parse function, like this:
let newDate= new Date(oldDate);
newDate.setMinutes(newDate.getMinutes() + newDate.getTimezoneOffset());
return newDate;