【问题标题】:angular material 2, change datepicker Date Format "MM/DD/YYYY" to "DD/MM/YYYY" strange behavior角度材料2、将datepicker日期格式“MM/DD/YYYY”改为“DD/MM/YYYY”的奇怪行为
【发布时间】:2018-03-05 15:50:10
【问题描述】:

我刚刚尝试将 angular material 2 date-picker 默认日期格式 MM/DD/YYYY 更改为 DD/MM/YYYYDD.MM .YYYY 或至少 DD-MM-YYYY

根据this questionthe documentation 中提到的

providers: [{provide: MD_DATE_FORMATS, useValue: MY_NATIVE_DATE_FORMATS}]

所以尝试了以下方法

Approach 1 plunkr : 获取 DD-MM-YYYY 格式

Approach 2 plunkr : 获取 DD.MM.YYYY 格式

Approach 3 plunkr : 获取 DD/MM/YYYY 格式

但是在我选择 Date 1 到 12 之前,上述每种方法都可以正常工作,

例如:今天的日期是 2017 年 9 月 25 日,如果我选择 2017 年 9 月 12 日 作为日期,然后再次单击 datepicker 按钮我可以看到日历日期,作为2017 年 11 月 9 日 (09/11/2017) 不像 (11/09/2017) ,这似乎是默认日期格式没有正确覆盖

【问题讨论】:

    标签: angular datepicker angular-material2


    【解决方案1】:

    providers: 数组下的app.module.ts 中使用它。

    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'}

    【讨论】:

    • 这是他一开始尝试的,但它仍然很奇怪
    • 谢谢你!我有同样的问题,我以前只用过'nl'。使用“nl-NL”它可以正常工作。
    • 是的,这确实有效,但您需要导入到您的 app.module 以及 import { MAT_DATE_LOCALE } from '@angular/material';
    • 太棒了..可能是最简单的方法...感谢分享
    • 这将有助于更改显示值而不是实际日期值。我得到这样格式的日期值“2020 年 10 月 30 日星期五 00:00:00 GMT+0600(孟加拉国标准时间)”
    【解决方案2】:

    1/ 文档:By cusomising the parse and display format with a custom date atapter

    在自定义的Date Adapter(你的是AppDateAdapter)中,添加一个parse方法,将新的日期格式(DD/MM/YYY)解析为日期有效日期:

    例如对于 DD/MM/YYYY 格式,解析可以是:

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

    工作堆栈闪电战:https://stackblitz.com/edit/angular-material-datepicker-format?embed=1&file=app/date.adapter.ts

    您的完整日期适配器:

    export class AppDateAdapter extends NativeDateAdapter {
        parse(value: any): Date | null {
            if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
              const str = value.split('/');
              const year = Number(str[2]);
              const month = Number(str[1]) - 1;
              const date = Number(str[0]);
              return new Date(year, month, date);
            }
            const timestamp = typeof value === 'number' ? value : Date.parse(value);
            return isNaN(timestamp) ? null : new Date(timestamp);
          }
       format(date: Date, displayFormat: any): 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);
       } 
    }
    

    这种方法的优点是您还可以在显示常量中自定义monthYearLabel 的格式,并且可以有一个如下所示的日历:

    【讨论】:

    • 谢谢,但将其更改为 2017/06/28 确实会导致奇怪的情况。
    • @Fetra R. 好吧,这么说吧:我只更改了这一行 return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year; to year + '/'+ this._to2digit(day) + '/' + this._to2digit(month);还不够吗?
    • 你刚刚添加的这个确实有效!谢谢!
    • 如果输入的是数字,这会坏掉......在格式化方法中添加一个“displayFormat”来保存选择的格式会不会很糟糕?
    • 如果“displayFormat”实际上是一个字符串,为什么它应该是一个对象?
    【解决方案3】:

    一种可能的解决方案是简单地定义您自己的输入格式:

    export const DD_MM_YYYY_Format = {
        parse: {
            dateInput: 'LL',
        },
        display: {
            dateInput: 'DD/MM/YYYY',
            monthYearLabel: 'MMM YYYY',
            dateA11yLabel: 'LL',
            monthYearA11yLabel: 'MMMM YYYY',
        },
    };
    
    @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css'],
        providers: [
            {provide: MAT_DATE_FORMATS, useValue: DD_MM_YYYY_Format},
        ]
    })
    export class AppComponent implemets OnInit {
       // ... some code
    }
    

    以下代码告诉注入器在请求MAT_DATE_FORMATS 时返回DD_MM_YYYY_Format(有关详细信息,请阅读here)。在您的自定义格式中,属性display.dateInput 设置为DD/MM/YYYY

    【讨论】:

      【解决方案4】:

      在您的 app.module.ts 文件中使用它,位于 provider 部分,如下所示

       providers: [
          {provide: MAT_DATE_LOCALE, useValue: 'en-GB'}
        ], 
      

      【讨论】:

        【解决方案5】:

        Fetrarij 的更新版本,日期格式为 dd.mm.yyyy,第一天为星期一:

        • 在 app.module.ts 中:
         
            { provide: MAT_DATE_LOCALE, useValue: 'sk-SK' },
        
        • 日期适配器扩展:
         
        
            @Injectable()
            export class DateAdapterSK extends NativeDateAdapter {
        
                getFirstDayOfWeek(): number {
                    return 1;
                }
        
                parse(value: any): Date | null {
                    if ((typeof value === 'string') && (value.indexOf('.') > -1)) {
                        const str = value.split('.');
                        const year = Number(str[2]);
                        const month = Number(str[1]) - 1;
                        const date = Number(str[0]);
                        return new Date(year, month, date);
                    }
                    const timestamp = typeof value === 'number' ? value : Date.parse(value);
                    return isNaN(timestamp) ? null : new Date(timestamp);
                }
        
            }
        
        

        为我工作。角 6。

        【讨论】:

        • 我已解决,仅包含部分代码 app.module.ts {provider}
        • 喜欢这个解决方案,正是我想要的!幸运的是,我只关心显示器,'en-GB' 也可以!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多