Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material DatePicker: Date becomes one day before selected date

I'm using latest Angular 4 and Angular-Material2-2.0.0-beta7. This is my template using MdDatePicker:

<md-input-container fxFlex="33" class="birthday-container">
    <input mdInput name="birthday" placeholder="Birthday" required [(ngModel)]="member.birthday" [mdDatepicker]="birthdayPicker">
    <button mdSuffix [mdDatepickerToggle]="birthdayPicker"></button>
</md-input-container>
<md-datepicker #birthdayPicker></md-datepicker>

In app.module, here is the provider:

{provide: DateAdapter, useClass: NativeDateAdapter}

And member.birthday is Date type. But when JSON.stringify(member.birthday), it becomes one day before the selected date. For example:

Select 2017-4-1 from date picker, and the stringified result is 2017-03-31T13:00:00.000Z.

This post raised the same question but I'm not sure how to apply moment.js to the code.

like image 779
Softhinker.com Avatar asked Jun 25 '17 08:06

Softhinker.com


People also ask

How to use datepicker with angular material?

For input event, Angular Material provides (dateInput) event for Datepicker. The dateInput triggers when user enters date manually in input box as well as selecting date from calendar. The dateInput event is bound to Datepicker input text.

What is (dateinput) event in Angular Material?

For input event, Angular Material provides (dateInput) event for Datepicker. The dateInput triggers when user enters date manually in input box as well as selecting date from calendar.

How do I use datepicker with time selection in material?

Using Datepicker with Time Selection. The @angular-material-components/datetime-picker package provides components to add Datepicker with Time selection capabilities. To create a Date and Time picker in Material, add the ngx-mat-datetime-picker component instead of mat-datepicker as shown below: <mat-form-field> <input matInput ...

How to get date and date range with custom date formats in angular?

Most of the Angular projects prefer the Material UI library due to its compatibility and ease of usage. We know by default the Material UI library only provides the Datepicker component using which we can get Date and Date range with custom date formats as well.


1 Answers

I solved it by creating a custom date adapter (which inherits the native date adapter) and overriding create-date method to remove timezone offset

@Injectable({        providedIn: 'root' }) 
export class CustomDateAdapterService extends NativeDateAdapter {    
    public createDate(year: number, month: number, date: number): Date {
        const localDate = super.createDate(year, month, date);
        const offset = localDate.getTimezoneOffset() * 60000;
        return new Date(localDate.getTime() - offset); // utcDate
    } 
}

you can have a look at complete gist here

like image 103
harishr Avatar answered Oct 16 '22 06:10

harishr