【问题标题】:Angular Material Datepicker input formatAngular Material Datepicker 输入格式
【发布时间】:2020-01-27 15:31:37
【问题描述】:

使用日期选择器选择日期时,一切正常,以所需格式显示日期:DD/MM/YYYY

但是当手动输入格式为DD/MM/YYYY 的日期时,日期选择器会自动将日期更改为MM/DD/YYYY,将第一个值DD 检测为月份。

如何使手动输入被检测为DD/MM/YYYY,而不是MM/DD/YYYY

谢谢!

<mat-form-field class="datepickerformfield" floatLabel="never">
    <input matInput class="dp" formControlName="fpresentaciondesde" [matDatepicker]="picker5" placeholder="DD/MM/YYYY" required>
    <mat-datepicker-toggle matSuffix [for]="picker5"></mat-datepicker-toggle>
    <mat-datepicker #picker5></mat-datepicker>
</mat-form-field>

【问题讨论】:

    标签: typescript angular-material mat-datepicker


    【解决方案1】:

    您需要像这样构建一个自定义日期适配器:

    export class CustomDateAdapter 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: Object): string {
        date = new Date(Date.UTC(
          date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(),
          date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
        displayFormat = Object.assign({}, displayFormat, { timeZone: 'utc' });
    
        const dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
        return dtf.format(date).replace(/[\u200e\u200f]/g, '');
      }
    
    }
    

    然后在您的应用中使用它:

    @NgModule({
        ....
        providers: [
            { provide: DateAdapter, useClass: CustomDateAdapter }
        ]
    })
    

    DEMO

    【讨论】:

    • 您可以返回 this.invalid() 而不是返回 null,这将在表单中触发验证。
    • 是的。我想知道为什么按回车后输入跳回“mm.dd.yyyy”。那是因为您的帖子回答了 OP 对 '/'-splitted "dd/mm/yyyy" 的问题,而我必须熟练使用它以用于点分割格式。真丢人!
    【解决方案2】:

    HTML 代码

    <mat-form-field>
    <input matInput placeholder=”Select Date” [matDatepicker]=”datepickerRef” name=”datepicker” ngModel #dateCtrl=”ngModel” required readonly/>
    <mat-datepicker-toggle [for]=”datepickerRef” matSuffix></mat-datepicker-toggle>
    <mat-datepicker #datepickerRef></mat-datepicker>
    <mat-error *ngIf=”dateCtrl.errors?.required && deptCtrl.touched”>Choose a Date</mat-error>
    </mat-form-field>
    

    这是写入文件名格式-datepicker.ts的辅助函数

    import { NativeDateAdapter } from ‘@angular/material’;
    import { MatDateFormats } from ‘@angular/material/core’;
    export class AppDateAdapter extends NativeDateAdapter {
      format(date: Date, displayFormat: Object): string {
        if (displayFormat === ‘input’) {
          let day: string = date.getDate().toString();
          day = +day < 10 ? ‘0’ + day : day;
          let month: string = (date.getMonth() + 1).toString();
          month = +month < 10 ? ‘0’ + month : month;
          let year = date.getFullYear();
          return `${day}-${month}-${year}`;
        }
        return date.toDateString();
      }
    }
    export const APP_DATE_FORMATS: MatDateFormats = {
      parse: {
        dateInput: { month: ‘short’, year: ‘numeric’, day: ‘numeric’ },
      },
      display: {
        dateInput: ‘input’,
        monthYearLabel: { year: ‘numeric’, month: ‘numeric’ },
        dateA11yLabel: { year: ‘numeric’, month: ‘long’, day: ‘numeric’
        },
        monthYearA11yLabel: { year: ‘numeric’, month: ‘long’ },
      }
    };
    

    在 providers 标签中提供上述实现。

    import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
    import { AppDateAdapter, APP_DATE_FORMATS } from 'src/app/shared/format-datepicker';
    @Component({
      providers: [
        {provide: DateAdapter, useClass: AppDateAdapter},
        {provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
      ]
    })
    

    我通过这篇文章尝试了这一点 https://amandeepkochhar.medium.com/angular-material-datepicker-set-custom-date-in-dd-mm-yyyy-format-5c0f4340e57 它有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多