角日期格式的Angular 6 matDatepicker

时间:2018-08-09 14:43:23

标签: angular datepicker momentjs

需要有关Angular 6 matDatepicker Moment的帮助。有两个日期选择器,一个用于MM / YYYY,另一个用于DD / MM / YYYY。所以问题是当我在第二个日期选择日期时,在输入字段上得到的是MM / YYYY而不是DD / MM / YYYY。开发者教程/信息,来自:https://material.angular.io/components/datepicker/overview

import {FormControl} from '@angular/forms';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';
import * as _moment from 'moment';
import { default as _rollupMoment, Moment } from 'moment';
const moment = _rollupMoment||_moment;
export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};
@Component({
  selector: 'myselector',
  templateUrl: 'my.html',
  styleUrls: ['my.css'],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
date = new FormControl(moment()); //for first datepicker
generalStartDate = new Date(new Date().getFullYear(), 0, 1);//for second datepicker

1 个答案:

答案 0 :(得分:5)

您必须为日期选择器2创建自定义日期选择器格式

  

我认为DEMO对您会有所帮助。

演示-----> multi-format-date-picker

HTML:

主要形式:

 date1 : Date ;
  date2 : Date ;

  catchDate1(event) {
    this.date1 = event;
  }

  catchDate2(event) {
    this.date2 = event;
  }

TS;

export const MY_FORMATS2 = {
  parse: {
    dateInput: 'DD/MM/YYYY',
  },
  display: {
    dateInput: 'DD/MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

日期格式2:

function getYesterdayRow(yesterdayDate,columnRange) {
    var displayValues = columnRange.getDisplayValues();
    for (var i = 0; i < displayValues.length; i++) {
        var displayValue = displayValues[i][0];
        if (displayValue === yesterdayDate) return i + 1;
    }
    return 0;
}