DEV Community

Cover image for Customize date picker in Angular
Alejandro
Alejandro

Posted on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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) {

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay