'How do I insert dots into date and limit the year in angular material date picker?

The component in Angular material datepicker:

inputEvent(event, type: number): void {...}
changeEvent(event, type: number): void {...}

newDateStart: Date = null;
endDateStart: Date = null;

The template:

<mat-date-range-input [rangePicker]="picker">
    <input #fromInput matStartDate placeholder="Start Date"
           (dateInput)="inputEvent($event, 0)"
           (dateChange)="changeEvent($event, 0)">
    <input #toInput matEndDate placeholder="End Date"
           (dateInput)="inputEvent($event, 1)"
           (dateChange)="changeEvent($event, 1)">
</mat-date-range-input>

And the CustomDateAdapter for datepicker:

export class CustomDateAdapter extends NativeDateAdapter {

  parse(value: any): Date | null {
    // if ((typeof value === 'string') && (value.indexOf('.') > -1)) {
    if (typeof value === 'string') {
      let str: string[] = [];

      if (value.indexOf('.') > -1) {
        str = value.split('.');
      } else if (value.indexOf(' ') > -1) {
        str = value.split(' ');
      } else if (value.indexOf('-') > -1) {
        str = value.split('-');
      }

      const year = Number(str[2]);
      const month = Number(str[1]) - 1;
      const date = Number(str[0]);

      return new Date(year, month, date);
    } else if ((typeof value === 'string') && value === '') {
      return new Date();
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }

  getFirstDayOfWeek(): number {
    return 1;
  }
}

The date format is 05.03.2022 where 05 - day, 03 - month, 2022 - year.

One may enter:

  1. "05032022" in this case I need to add "." into this string to get "05.03.2022" and plase this new string into input in the template
  2. "05.03.202200" in this case I need to limit the year by 4 number length

How do I insert dots into date and limit the year in angular material date picker?



Solution 1:[1]

use input type date and that will take care of the validations.

<input type="date" (dateChange)="changeEvent($event)">

dateChange(e){
    let date = new Date(e.target.value);
    let month = date.getMonth();
    let day = date.getDate();
    let year = date.getFullYear();
    let formatedDate = month +'.' + day + '.'+ year;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mow