loading...
Cover image for Customize date picker in Angular

Customize date picker in Angular

amatosg profile image Alejandro Matos πŸ‡΅πŸ‡ͺ ・2 min read

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;
  }
}

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

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

Et voila, you will have it your way :)

Alt Text

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

Posted on by:

amatosg profile

Alejandro Matos πŸ‡΅πŸ‡ͺ

@amatosg

Uneployed Full Stack developer with deep knowledge in Java & Angular, also SQL

Discussion

pic
Editor guide