如何在角度材料日期选择器中更改日期格式? [英] How can I change date format in angular material datepicker?

查看:34
本文介绍了如何在角度材料日期选择器中更改日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将默认日期格式 (YYYY-MM-DD) 更改为其他格式,例如 (MM-DD-YYYY).

I want to change the default date format (YYYY-MM-DD) to some other format like (MM-DD-YYYY).

这是我的日历 HTML 结构.

This is my calendar HTML structure.

 <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>

推荐答案

有一篇关于它的博客:https://blog.angular.io/taking-角度材料日期选择器的优势 237e80fa14b3

(以防 URL 无效),例如,假设您已经在整个应用中使用 Moment.js,您可以创建一个 MomentDateAdapter:

(in case the URL becomes invalid), For example, say you’re already using Moment.js throughout your app, you can create a MomentDateAdapter:

继承一个类

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, f.e. in a separate typescript file:

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.

这篇关于如何在角度材料日期选择器中更改日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆