如何更改角度材质的日期选择器格式

时间:2018-11-18 09:49:12

标签: angular date angular-material2

这是我使用棱角材质的日期选择器时得到的日期格式。...Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time)

但是我需要(YYYY-MM-DD)(YYYY-MM-DDTHH:mm)这种格式的日期。

这是我用来从角形材料形式捕获数据的模型类

export class FlightSchedule {

    constructor(
        public destination: string,
        public origin: string,
        public date: string,
        public limit: string
    ) {}

}

请帮助我,我无法将日期转换为YYYY-MM-DDYYYY-MM-DDTHH:mm格式。

我是Angular的新手

预先感谢

4 个答案:

答案 0 :(得分:10)

无需使用MomentDateAdapter

这是我使用MAT_NATIVE_DATE_FORMATS使用最少代码的解决方案。

  1. 声明您自己的日期格式
import { MatDateFormats, MAT_NATIVE_DATE_FORMATS } from '@angular/material';

export const GRI_DATE_FORMATS: MatDateFormats = {
  ...MAT_NATIVE_DATE_FORMATS,
  display: {
    ...MAT_NATIVE_DATE_FORMATS.display,
    dateInput: {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    } as Intl.DateTimeFormatOptions,
  }
};
  1. 使用它们
@Component({
  selector: 'app-vacation-wizard',
  templateUrl: './vacation-wizard.component.html',
  styleUrls: ['./vacation-wizard.component.scss'],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: GRI_DATE_FORMATS },
  ]
})

别忘了设置适当的语言!

constructor(private readonly adapter: DateAdapter<Date>) {}
this.adapter.setLocale(this.translate.currentLang);

仅此而已!

答案 1 :(得分:2)

您需要提供一个包含您要使用的格式的对象。该对象应类似于:

export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'YYYY-MM-DD',
    monthYearLabel: 'YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'YYYY',
  },
};

然后,您需要将其添加到您的provider数组中,如下所示:

  import { MAT_DATE_FORMATS } from '@angular/material';
  import { MomentDateAdapter } from '@angular/material-moment-adapter';

  //...

  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],

Here is a StackBlitz demo to show it working

答案 2 :(得分:2)

mask = df['B'].eq(6)
#alternative
#mask = (df['B'] == 6)
df['No_of_6'] = mask.astype(int).groupby(df['Id']).transform('sum')

在您的app.module中添加以上代码。它对我来说很完美。

答案 3 :(得分:0)

  modelChanged(date) {
    var theDate = new Date(Date.parse(date));
    const localDate = theDate.toLocaleString().split(" ");

    console.log(localDate);
  }
    <!--I had the same issue and found it that with javascript was simple approach
--->
    
    <mat-form-field class="example-full-width" appearance="fill">
          <mat-label>Choose a date</mat-label>
          <input
            matInput
            [matDatepicker]="picker"
            [(ngModel)]="date"
            (ngModelChange)="modelChanged($event)"
          />
          <mat-datepicker-toggle
            matSuffix
            [for]="picker"
          ></mat-datepicker-toggle>
          <mat-datepicker touchUi #picker color="primary"></mat-datepicker>
        </mat-form-field>