【问题标题】:Angular Mat datepicker formattingAngular Mat 日期选择器格式
【发布时间】:2018-11-14 01:47:43
【问题描述】:

我想在日期选择器中以 MON YYYY 格式显示日期。当用户单击任何日期时,我只想显示月份和年份,日期对我没有用,但我在数据库(Oracle)中有字段作为日期时间,因此不能以字符串格式传递日期。

例如:如果用户选择 2018 年 11 月 14 日,则希望将日期显示为 2018 年 11 月,但在数据库中我希望将其显示为 2018 年 11 月 1 日(无论日期选择如何,都需要默认将日期设置为 1)

【问题讨论】:

    标签: angular


    【解决方案1】:

    Angular 材质日期选择器没有任何我们可以直接应用日期格式的方法或属性,但在 @angular/material 库的帮助下,您可以自定义格式化服务。

    HTML:

    <mat-form-field>
        <input matInput [matDatepicker]="dp" placeholder="select date" (dateChange)="onChange($event.value)">
        <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
        <mat-datepicker #dp startView="month"></mat-datepicker>
    </mat-form-field>
    

    第一步:导入所需的类和常量变量。

    import { NativeDateAdapter, MAT_DATE_FORMATS, DateAdapter } from "@angular/material";
    

    Step2:使用NativeDateAdapter类方法进行格式化。

    const months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
    export class AppDateAdapter extends NativeDateAdapter {
    
      format(date: Date, displayFormat: Object): string {
        if (displayFormat === 'input') {
          const day = date.getDate();
          const month = date.getMonth();
          const year = date.getFullYear();
          return `${months[month]} ${year}`;
        }
        return date.toDateString();
      }
    }
    

    第三步:声明日期格式常量。

    export const APP_DATE_FORMATS =
    {
      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' },
      }
    };
    

    第四步:在组件或主模块下注册提供者

    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.scss'],
      providers: [
        {
          provide: DateAdapter, useClass: AppDateAdapter
        },
        {
          provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
        }
      ]
    })
    export class TestComponent {
      constructor() { }
    
      onChange(val) {
        var d = new Date(val);
        let date = [d.getFullYear(), ('0' + (d.getMonth() + 1)).slice(-2), ('01').slice(-2)].join('-');
        console.log(date);
          }
    }
    

    选择:2018 年 2 月 14 日

    展示:2018 年 2 月

    输出:2018-02-01(在.ts文件中)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      相关资源
      最近更新 更多