【问题标题】:How to change the time format in datepicker?如何更改日期选择器中的时间格式?
【发布时间】:2019-01-28 11:14:41
【问题描述】:

我使用 Angular Material 及其 Datepicker 组件。我在做报告时遇到了问题。所有日期都以这种方式显示。

2019 年 1 月 25 日星期五 00:00:00 GMT 0500(叶卡捷琳堡,标准时间)

我需要报告中的日期采用这种格式25.01.2019

我尝试不使用 datepicker 组件,所有日期都正常显示,但我不想没有这个组件工作。

如何解决这个问题?

ts:

import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Report } from "../../../../shared/interfaces";

import * as _moment from 'moment';
const moment = _moment;

@Component({
  selector: 'app-report',
  templateUrl: './report.component.html',
  styleUrls: ['./report.component.scss']
})

export class ReportComponent {

  selectedReport: Report
  report_url: string = 'http://localhost:3000' + '/reports/svod'
  selectedDate: string = moment().format('YYYY-MM-DD')

  constructor(
    public dialogRef: MatDialogRef<ReportComponent>,
    @Inject(MAT_DIALOG_DATA)
    public data: any
  ) { 
    this.selectedReport = new Report()
  }

  onSelectDate(event): void {
    this.selectedReport = new Report()
    this.selectedDate = event
  }

}

html:

<mat-form-field>
  <input matInput [ngModel]="selectedDate" [matDatepicker]="dp" (ngModelChange)="onSelectDate($event)" >
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker #dp></mat-datepicker>
</mat-form-field>

【问题讨论】:

  • 自己解决了问题

标签: angular angular-material


【解决方案1】:

你可以试试这个来格式化日期:

  onSelectDate(event): void {
    this.selectedReport = new Report()
    this.selectedDate = formatDate(event, 'dd/MM/yyyy', 'en-US') // Try to convert here
  }

【讨论】:

  • 之后,我无法选择数据库中没有的日期
【解决方案2】:

正如docs 中所建议的,您需要提供语言环境以使用最佳格式。所以对你来说,它应该是这样的:


@Component({
  selector: 'app-report',
  templateUrl: './report.component.html',
  styleUrls: ['./report.component.scss'],
  providers: [
    { provide: DateAdapter, useClass: MyDateAdapter, deps: [MAT_DATE_LOCALE] },
    { provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMAT },
    { provide: MAT_DATE_LOCALE, useValue: "**YOUR LOCALE**" }
  ]
})

export const CUSTOM_DATE_FORMAT: MatDateFormats = {
  parse: {
    dateInput: 'DD.MM.YYYY',
  },
  display: {
    dateInput: 'DD.MM.YYYY',
    monthYearLabel: 'MMMM YYYY',
    dateA11yLabel: 'DD.MM.YYYY',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

【讨论】:

  • 我也这样做了,但是我的报告中显示了一组数字来代替日期 (1548356400000)
  • @user10966440 可能会尝试这样做:this.selectedDate = new Date(moment().format('YYYY-MM-DD'));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多