简体   繁体   中英

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

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 least DD-MM-YYYY

According to this question and as mentioned in the documentation

providers: [{provide: MD_DATE_FORMATS, useValue: MY_NATIVE_DATE_FORMATS}]

So tried following approaches

Approach 1 plunkr : to get in DD-MM-YYYY format

Approach 2 plunkr : to get in DD.MM.YYYY format

Approach 3 plunkr : to get in DD/MM/YYYY format

but each of above approach working ordinary until I select a Date 1 to 12,

for ex: Today date is 25th September 2017 , if I select 12th September 2017 as date, then once click datepicker button again I can see calender date, taken as 09th of November 2017(09/11/2017) not as (11/09/2017) , which is seems default date format not override correctly

在您的app.module.ts下的providers:数组中使用它。

{provide: MAT_DATE_LOCALE, useValue: 'en-GB'}

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:

在此处输入图片说明

One of possible solution is simply defining your own input format:

export const DD_MM_YYYY_Format = {
    parse: {
        dateInput: 'LL',
    },
    display: {
        dateInput: 'DD/MM/YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
    },
};

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [
        {provide: MAT_DATE_FORMATS, useValue: DD_MM_YYYY_Format},
    ]
})
export class AppComponent implemets OnInit {
   // ... some code
}

The following code tells the injector to return a DD_MM_YYYY_Format when something asks for the MAT_DATE_FORMATS (read here for more details). Inside your custom format, property display.dateInput is set to DD/MM/YYYY .

Use it on your app.module.ts file under provider's section as below

 providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'}
  ], 

Updated version of Fetrarij, for date format dd.mm.yyyy with first day monday:

  • in app.module.ts:

    { provide: MAT_DATE_LOCALE, useValue: 'sk-SK' },
  • date adapter extension:


    @Injectable()
    export class DateAdapterSK extends NativeDateAdapter {

        getFirstDayOfWeek(): number {
            return 1;
        }

        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);
        }

    }

Work for me. Angular 6.

只需检查https://material.angular.io/components/datepicker/overview页面上的“ 自定义解析和显示格式”部分

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM