Angular 2 Material 2 datepicker 日期格式 [英] Angular 2 Material 2 datepicker date format

查看:31
本文介绍了Angular 2 Material 2 datepicker 日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need help. I don't know how to change the date format of the material 2 datepicker. I've read documentation but I don't understand what I actually need to do. Output date format which datepicker provides by default is f.e.: 6/9/2017

我想要实现的是将格式更改为 2017 年 6 月 9 日或任何其他格式.

What I'm trying to achieve is to change format to the 9-Jun-2017 or any other.

文档https://material.angular.io/components/component/datepicker根本没有帮助我.提前致谢

Documentation https://material.angular.io/components/component/datepicker doesn't help me at all. Thanks in advance

推荐答案

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

Here is the only solution I found for this one:

首先创建常量:

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:

Then you have to extend 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);
   } 
}

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

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

And the last step, you have to add it into module providers:

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

就是这样.我不敢相信没有一些简单的方法可以通过@Input 更改日期格式,但我们希望它会在未来的材料 2 版本(当前 beta 6)中实现.

And that's it. I can not believe that there is no some easy way to change date format through the @Input but let's hope it will be implemented in some future version of material 2 (currently beta 6).

这篇关于Angular 2 Material 2 datepicker 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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