Angular Material DateTimePicker shows wrong format in input

1.1k views Asked by At

I want to customize it for my input fields and I can do it separately but it's not working when I put them together.

The first thing is I wanted to format is to set the calendars first day of the week from sunday to monday, I managed to do it with a custom adapter:

export class CustomDateAdapter extends NgxMatNativeDateAdapter {
    getFirstDayOfWeek(): number {
        return 1;
    }
}

The second was to format the date time like this: 2021-04-21 8:00, and it works well with this code:

const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
  parse: {
    dateInput: 'l, LT'
  },
  display: {
    dateInput: 'YYYY-MM-DD HH:mm',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  }
};

The problem is if I use them together the date time format switches back to 2021/04/21 and time is missing, although the calendar starts with monday which is fine but the format is not. I can't figure it out why the date time format is not working after I use the custom calendar format. Any ideas?

1

There are 1 answers

0
Andy N On

The solution, which worked for me, was:

1/ Define a CustomDateAdapter and implement the methods: getFirstDayOfWeek and format

// Filename 'custom-date-adapter.ts'

import { NgxMatNativeDateAdapter } from '@angular-material-components/datetime-picker';
import * as moment from 'moment';

export class CustomDateAdapter extends NgxMatNativeDateAdapter {
  getFirstDayOfWeek(): number {
    // Monday is the first day of the week
    return 1;
  }

  // Format the date, according to CUSTOM_DATE_FORMATS
  format(date: Date, displayFormat: Object): string {
    return moment(date).format(displayFormat.toString());       
  }  
}

2/ Then, within your module, use:

...
  const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
    parse: {
      dateInput: 'l, LTS'      
    },
    display: {    
      dateInput: 'DD.MM.YYYY HH:mm:ss',
      monthYearLabel: 'MMM YYYY',
      dateA11yLabel: 'LL',
      monthYearA11yLabel: 'MMMM YYYY'
    },  
  };
...

providers: [
{ provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
{ provide: NgxMatDateAdapter, useClass: CustomDateAdapter},
],

See: DateTimePicker Example