简体   繁体   English

如何更改角形材料日期选择器中的日期格式?

[英]How can I change date format in angular material datepicker?

I want to change the default date format (YYYY-MM-DD) to some other format like (MM-DD-YYYY). 我想将默认日期格式(YYYY-MM-DD)更改为其他格式,例如(MM-DD-YYYY)。

This is my calendar HTML structure. 这是我的日历HTML结构。

 <mat-form-field class="full-width">
                        <input matInput [matDatepicker]="picker"
                               [(ngModel)]="currentDay"
                               (dateChange)="currentDayChanged()"
                               required
                               placeholder="date"
                               name="currentDay">
                        <mat-datepicker-toggle matSuffix
                                               [for]="picker">
                        </mat-datepicker-toggle>
                        <mat-datepicker #picker></mat-datepicker>
                    </mat-form-field>

There is a blog about it: https://blog.angular.io/taking-advantage-of-the-angular-material-datepicker-237e80fa14b3 有一个关于它的博客: https : //blog.angular.io/taking-advantage-of-the-angular-material-datepicker-237e80fa14b3

(in case the URL becomes invalid), For example, say you're already using Moment.js throughout your app, you can create a MomentDateAdapter: (以防URL无效),例如,假设您已经在整个应用程序中使用Moment.js ,则可以创建MomentDateAdapter:

Inherit a class 继承一个类

class MomentDateAdapter extends DateAdapter<Moment> {
  parse(value: any, parseFormat: any): Moment {
    return moment(value, parseFormat);
  }

  // Implementation for remaining abstract methods of DateAdapter.
}

Create a const like this, fe in a separate typescript file: 在单独的打字稿文件中创建一个这样的const fe:

const MOMENT_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    monthYearLabel: 'MMM YYYY',
    // See DateFormats for other required formats.
  },
};

finally provide both of these things in your application module 最后在您的应用程序模块中同时提供这两个东西

@NgModule({
  imports: [MdDatepickerModule, ...],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter},
    {provide: MD_DATE_FORMATS, useValue: MOMENT_FORMATS},
  ],
})
class AppModule {}

I appreciate if you let us know your results. 如果您让我们知道您的结果,我们将不胜感激。

Set in AppModule your locale! 在AppModule中设置您的语言环境!

Example for Brazil, 以巴西为例,

 import { LOCALE_ID } from '@angular/core'; import localePt from '@angular/common/locales/pt'; registerLocaleData(localePt, 'pt-BR'); @NgModule({ declarations: [ AppComponent ], imports: [], providers: [ { provide: LOCALE_ID, useValue: 'pt-BR' } ], bootstrap: [AppComponent] }) export class AppModule { } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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