angular material 2, change datepicker Date Format “MM/DD/YYYY” to “DD/MM/YYYY” strange behavior

后端 未结 5 957
离开以前
离开以前 2020-12-05 07:26

I just tried to change the angular material 2 date-picker default Date Format MM/DD/YYYY to DD/MM/YYYY or DD.MM.YYYY or at

5条回答
  •  甜味超标
    2020-12-05 07:59

    1/ DOCS: By cusomising the parse and display format with a custom date atapter

    In the custom Date Adapter (yours is AppDateAdapter), add a parse method to parse the new date format (DD/MM/YYY) to a date valid date:

    for example for the DD/MM/YYYY format, parse could be:

       parse(value: any): Date | null {
        if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
          const 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);
        }
        const timestamp = typeof value === 'number' ? value : Date.parse(value);
        return isNaN(timestamp) ? null : new Date(timestamp);
      }
    

    working stackblitz: https://stackblitz.com/edit/angular-material-datepicker-format?embed=1&file=app/date.adapter.ts

    your complete date adapter:

    export class AppDateAdapter extends NativeDateAdapter {
        parse(value: any): Date | null {
            if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
              const 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);
            }
            const timestamp = typeof value === 'number' ? value : Date.parse(value);
            return isNaN(timestamp) ? null : new Date(timestamp);
          }
       format(date: Date, displayFormat: any): string {
           if (displayFormat == "input") {
               let day = date.getDate();
               let month = date.getMonth() + 1;
               let year = date.getFullYear();
               return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
           } else {
               return date.toDateString();
           }
       }
    
       private _to2digit(n: number) {
           return ('00' + n).slice(-2);
       } 
    }
    

    The advantage of this approach is you could also custom the format of monthYearLabel in the display constants and could have a calendar which looks like:

提交回复
热议问题