如何为日期选择器实现 MD_DATE_FORMATS? [英] How to implement MD_DATE_FORMATS for datepicker?

查看:22
本文介绍了如何为日期选择器实现 MD_DATE_FORMATS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 material2 中闪亮的新日期选择器实现我自己的日期格式.根据文档,我必须提供我的 MD_DATE_FORMATS 版本:

I'm trying to implement my own date format for shiny new datepicker from material2. According to documentation i have to provide my version of MD_DATE_FORMATS:

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

当我使用默认实现时:

export const MD_NATIVE_DATE_FORMATS: MdDateFormats = {
  parse: {
    dateInput: null,
  },
  display: {
    dateInput: {year: 'numeric', month: 'numeric', day: 'numeric'},
    monthYearLabel: {year: 'numeric', month: 'short'},
    dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
    monthYearA11yLabel: {year: 'numeric', month: 'long'},
  }
};

我收到一个错误,指出日期输入为空.但它究竟是什么类型?文档说任何.

I get an error that date input is null. But what type it really is? Documentation says any.

如果我尝试放置一些虚拟函数,则会出现错误:_dateAdapter.parse is not a function.

If i try to put some dummy function there i get error: _dateAdapter.parse is not a function.

function dateInput() {
    return 'ddd';
}
const MY_DATE_FORMATS: MdDateFormats = Object.assign({}, MD_NATIVE_DATE_FORMATS, {parse: dateInput });

如何让它发挥作用?

推荐答案

非常感谢推动解决方案的@MariusR.如上所述,您需要提供自己的日期适配器.从plunkr来看,这很简单如下:

Many thanks to @MariusR who pushed the solution. As stated you need to provide your own date adapter. From the plunkr, this is as simple as follows:

export class OurDateAdapter extends NativeDateAdapter {
  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
      const str = value.split('/');
      return new Date(Number(str[2]), Number(str[1])-1, Number(str[0]), 12);
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }
}

这可以是您的任何 TS 文件,只需在您的组件模块中使用日期选择器提供:

This can be any of your TS files and just needs to be provided in the module of your component with the date picker:

  providers: [
    {provide: DateAdapter, useClass: OurDateAdapter}
  ]

在您的组件中,您需要在构造函数中使用它:

In your component you need to use it in the constructor:

  constructor(private dateAdapter: DateAdapter<Date>) {
    this.dateAdapter.setLocale('en-GB');
  }

可以在此处收集语言环境列表,plunkr 示例使用葡萄牙语,我的是英国英语.

The list of locales can be gathered here, the plunkr example uses Portuguese, mine is UK English.

http://www.i18nguy.com/unicode/language-identifiers.html

MariusR,鞠躬,为什么官方文档没有这个?

MariusR, take a bow, why can't the official docs have this?

这篇关于如何为日期选择器实现 MD_DATE_FORMATS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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