DEV Community

Cover image for Customize date picker in Angular
Alejandro
Alejandro

Posted on

Customize date picker in Angular

Versión en castellano: https://dev.to/amatosg/formateando-selector-de-fechas-en-angular-3p8i

When dealing with dates, formatting is crucial to understand each other: 12/01/2020 is not the same as 01/12/2020.

So an input field having the proper format is actually pretty important. With Angular this can be tricky as NgbDateParserFormatter will display dates using yyyy-MM-dd format:

Alt Text

I've been postponing this issue for too long, so I decided to fix it and display the proper dd/MM/yyyy format every region uses (if there is any region not using it, well...they should).

Custom Formatter

We need to create a new file, I called it shared/component/ngb-custom-date-parser-formatter.ts containing the following code:



import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';
import * as moment from 'moment';

@Injectable()
export class NgbCustomDateParserFormatter extends NgbDateParserFormatter {

  constructor(private momentFormat: string) {
    super();
  };

  format(date: NgbDateStruct): string {
    if (date === null) {
      return '';
    }
    const d = moment({ year: date.year,
      month: date.month - 1,
      date: date.day });
    return d.isValid() ? d.format(this.momentFormat) : '';
  }

  parse(value: string): NgbDateStruct {
    if (!value) {
      return null;
    }
    const d = moment(value, this.momentFormat);
    return d.isValid() ? { year: d.year(),
      month: d.month() + 1,
      day: d.date() } : null;
  }
}


Enter fullscreen mode Exit fullscreen mode

Then, in my app.module.ts I added the following line to the providers section:



{
    provide: NgbDateParserFormatter,
    useValue: new NgbCustomDateParserFormatter("DD/MM/YYYY") // <== format!
}


Enter fullscreen mode Exit fullscreen mode

Et voila, you will have it your way :)

Alt Text

PD: hopefully this will make it to the next release of JHipster ;)

Top comments (1)

Collapse
 
lancescape profile image
lancescape

FYI to get this to work you need to remove the "@Injectable" and change the constructor to:
constructor(@Inject(String) private momentFormat: string) {