angular-material-components icon indicating copy to clipboard operation
angular-material-components copied to clipboard

Set date and time format at runtime

Open chrisonline opened this issue 4 years ago • 1 comments

To format the date and time from the date and time picker we need to create a const with the desired date and time format like this:

const CUSTOM_MOMENT_FORMATS: NgxMatDateFormats = {
  parse: {
    dateInput: "L, LT"
  },
  display: {
    dateInput: "DD/MM/YYYY HH:mm",
    monthYearLabel: "MMM YYYY",
    dateA11yLabel: "LL",
    monthYearA11yLabel: "MMMM YYYY"
  }
};

And in the @Component section it needs to be set as provider like this:

providers: [
    { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_MOMENT_FORMATS } // Custom Date Format
  ]

But how can I set the date and time format dynamically. For example I have set the date and time format in the user settings and want to use this format here.

chrisonline avatar Apr 03 '21 13:04 chrisonline

Instead of using useValue in @Component providers, do useClass:

providers: [
    { provide: NGX_MAT_DATE_FORMATS, useClass: CustomDateFormat } // Custom Date Format
  ]

Define the class with internal variable and getters for display and parse:

export class CustomDateFormat {
  format = true;
  constructor() { }

  get display() {
    return {
      dateInput: this.format ? 'l, LTS' : 'l',
      monthYearLabel: 'MMM YYYY',
      dateA11yLabel: 'L',
      monthYearA11yLabel: 'MMMM YYYY',
    }
  }

  get parse() {
    return { dateInput: this.format ? 'l, LTS' : 'l' }
  }
}

Inject the provider to constructor of your component to access to the variable 'format': constructor(@Inject(NGX_MAT_DATE_FORMATS) public config: CustomDateFormat) { }

Now you can change the formats inside your component , like:

const ONLYDATE = false, DATEANDTIME = true;
this.config.format = ONLYDATE;
this.config.format = DATEANDTIME;

Ollizman avatar Sep 08 '21 06:09 Ollizman