javascript - Angular 2 Material 2日期选择器日期格式

标签 javascript angular angular-material2

我需要帮助。我不知道如何更改 Material 2 日期选择器的日期格式。我已经阅读了文档,但我不明白我实际需要做什么。 datepicker默认提供的输出日期格式f.e.: 6/9/2017

我想要实现的是将格式更改为 9-Jun-2017 或任何其他格式。

文档 https://material.angular.io/components/component/datepicker根本帮不了我。 提前致谢

最佳答案

这是我找到的唯一解决方案:

首先,创建常量:

const MY_DATE_FORMATS = {
   parse: {
       dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
   },
   display: {
       // dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
       dateInput: 'input',
       monthYearLabel: {year: 'numeric', month: 'short'},
       dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
       monthYearA11yLabel: {year: 'numeric', month: 'long'},
   }
};

然后你必须扩展 NativeDateADapter:

export class MyDateAdapter extends NativeDateAdapter {
   format(date: Date, displayFormat: Object): 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);
   } 
}

在格式功能中,你可以选择你想要的任何格式

最后一步,您必须将其添加到模块提供程序中:

providers: [
    {provide: DateAdapter, useClass: MyDateAdapter},
    {provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},
],

就是这样。我不敢相信没有什么简单的方法可以通过@Input 更改日期格式,但我们希望它会在 Material 2 的某个 future 版本(目前是 beta 6)中实现。

关于javascript - Angular 2 Material 2日期选择器日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44452966/

相关文章:

javascript - 需要时调用函数

javascript - Safari 上的 JS 错误 : Unexpected token '='

angular - 在可视化代码中调试 Angular/Typescript 将 '_1' 附加到变量

angular - 如何在firebase中将电子邮件验证码发送到用户电子邮件

angular - 如何启用和禁用基于选择表单的垫按钮

javascript - 谷歌街景中一个像素离地面的高度/海拔

javascript - 如何使用js或php接收表单元素并根据MLA和APA格式对它们进行排序?

angular - 如何在 Angular(v2 起) react 形式中找到无效控件

angular - 如何从 Mat-tab 或 Mat-card( Angular Material )中删除滚动条

Angular 2 Material 设计响应表