1
votes

on the basic date picker, if I manually enter a year (2019) and tab out, why does the date default to 12/31/2018?

https://material.angular.io/components/datepicker/overview

How do we change this behavior?

1

1 Answers

0
votes

The reason is that the date picker component seems to parse input string by passing it to the standard Date() constructor, which in some cases may give inconsistent results, see this SO post for details: Why does Date.parse give incorrect results?

You are probably in a timezone with negative UTC offset, so new Date("2019") gives you something like Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time)

In this particular case (a four digit string) you can fix this behavior by manually converting the string to Date like this: new Date(year, 0) in onChange event handler, but keep in mind that there may be other weird cases, like this for instance: 2019-01-01 -> 12/31/2018

component.html

<input [(ngModel)]="date" matInput #datepickerInput [matDatepicker]="picker" (dateChange)="onDateChange()"> 

component.ts

@ViewChild("datepickerInput", {static: false}) datepickerInput: ElementRef;
private date: Date = null;

private onDateChange() {
    if (this.datepickerInput.nativeElement.value.match(/^\s*\d{4}\s*$/)) {
        this.date = new Date(this.datepickerInput.nativeElement.value, 0);
    }
}