Home > database >  Angular Material Date picker 1 day behind when changing date
Angular Material Date picker 1 day behind when changing date

Time:06-25

This is a pretty common problem that people have asked about and I fixed my original issue using information from this question: Angular Material Datepicker shows one day behind in Angular 9 when I click search button

I assume that this was an issue because as the question states the date picker is defaulting to local time for me, which is MTN instead of UTC which I need it to be.

All I did was concatenate T00:00:00 to the end of my date values when I get them in the NgOnInit function and the dates began to appear correctly in the date picker:

  this.adjustData.forEach((element) => {
            element.checkoutDate = element.checkoutDate   'T00:00:00';
          });

However, when I change the date the value in the date field changes to the day before the date I select despite the value of the date being correct. For example, if I change checkoutDate to the 22nd from the 23rd the value of checkoutDate is correct when logged to the console but it appears in the date picker as the 21st.

This is my date picker:

<mat-form-field id="datePicker{{adj.checkoutDate}}"  appearance="fill" type="date">
            <mat-label>Choose a date</mat-label>
            <input matInput [min]="yesterday" [max]="today" [matDatepicker]="picker" value="{{adj.checkoutDate}}" (dateChange)="onChangeDate($event, adj)">
            <mat-hint>MM/DD/YYYY</mat-hint>
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

There must be a more robust way to correct this issue but I'm not sure what it is. If you need any further information to help answer this question I would be happy to provide it.

CodePudding user response:

Indeed, it is a pretty common problem and the typical culprit is daylight saving time or conversion between local and target time which results in the wrong date.

For a simple naive solution, if you only care about date set the time to T12:00:00 - so even if it shifts a couple of hours here/there at least you will have the correct date.

Other solution would be just to use/save/read the date. As material calendar can also consume dates. But that also won't work if your backend or database assumes correct timestamps.

  <input matInput [matDatepicker]="picker" value="2022-06-24">

Probably the most robust way would to save the date as ISO timestamp (without timezone) and when reading back, not to transform it into local time, not to account for DLS just read the face value of the ISO date string - can't go wrong that way?

  • Related