MdDatepickerModule - 欧洲格式 [英] MdDatepickerModule - European format

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

问题描述

我使用 MdDatePickerModule 来选择日期,但我有一个问题:如果我选择 8 月 5 日,则一切正常.但是如果我重新打开选择,月份就会改变并变成五月,如果我选择 5 月 3 日,我关闭,重新打开,月份是三月.现在我知道问题是在美国,与欧洲相比,月和日是颠倒的,但解决冲突的聪明"方法是什么?谢谢

I use MdDatePickerModule to pick dates but I have a problem: If I select August 5, everything is ok. But if I reopen the selection the month changes and becomes May, if I select May 3, I close, re-open, the month is March. Now I know that the problem is that in America the month and the day are inverted compared to Europe, but what is the "smart" way to resolve the conflict. thanks

推荐答案

目前正确的做法是设置语言环境以及使用自定义适配器来正确解析日期.

The correct way of doing it for now is to set the locale as well as having a custom adapter to parse the date properly.

ts:

import {Component} from '@angular/core';
import { NativeDateAdapter, DateAdapter, MD_DATE_FORMATS } from "@angular/material";

export class ItalianDateAdapter extends NativeDateAdapter {
  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
      const str = value.split('/');
      if (str.length < 2 || isNaN(+str[0]) || isNaN(+str[1]) || isNaN(+str[2])) {
        return null;
      }
      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);
  }
}

@Component({
  selector: 'datepicker-overview-example',
  templateUrl: './datepicker-overview-example.html',
  styleUrls: ['./datepicker-overview-example.css'],
  providers: [{provide: DateAdapter, useClass: ItalianDateAdapter}],
})
export class DatepickerOverviewExample {

  locale: string;

  constructor(private dateAdapter: DateAdapter<Date>) {
    this.locale = 'it';
    this.dateAdapter.setLocale('it');   
  }

}

Plunker 演示

此错误已报告给 Material 团队并通过以下问题进行跟踪.

This bug has been reported to Material team and being tracked by the following issue.

这篇关于MdDatepickerModule - 欧洲格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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