Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 matDatepicker with Moment date format

Need some help regarding Angular 6 matDatepicker Moment. There are two date pickers, one for MM/YYYY and the other for DD/MM/YYYY. So the issue is when I pick a date on the second, I get MM/YYYY on the input field instead of DD/MM/YYYY. dev tutorial/info from: 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
like image 446
Michael Seltene Avatar asked Dec 23 '22 05:12

Michael Seltene


1 Answers

You have to create custom date picker format for date picker 2

I think DEMO will be helpful for you.

DEMO -----> multi-format-date-picker

HTML:

in main form :

 <app-datepicker1 (date1)="catchDate1($event)"></app-datepicker1>
<app-datepicker2 (date2)="catchDate2($event)"></app-datepicker2>

TS;

 date1 : Date ;
  date2 : Date ;

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

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

Date format 2 :

export const MY_FORMATS2 = {
  parse: {
    dateInput: 'DD/MM/YYYY',
  },
  display: {
    dateInput: 'DD/MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};
like image 71
Akj Avatar answered Jan 13 '23 10:01

Akj