DEV Community

Cover image for Formateando Selector de fechas en Angular
Alejandro
Alejandro

Posted on

Formateando Selector de fechas en Angular

English version: https://dev.to/amatosg/customize-date-picker-in-angular-4323

Cuando se manejan fechas, el formato es crucial para que nos podamos entender correctamente: 12/01/2020 no es lo mismo que 01/12/2020.

Esto nos dice que un campo de fecha, es realmente importante. Con Angular, esto puede ser complicado, ya que NgbDateParserFormatter mostrará las fechas con el formato yyyy-MM-dd:

Alt Text

Estuve procastinando con esto durante mucho tiempo, así que decidí tomar cartas en el asunto y mostrar el formato correcto (el que todos deberían usar): dd/MM/yyyy

Custom Formatter

Lo que necesitamos hacer es crear un archivo, yo lo llamé shared/component/ngb-custom-date-parser-formatter.ts y puse el siguiente código:

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

Luego, en mi app.module.ts agregué lo siguiente en la sección providers:

{
    provide: NgbDateParserFormatter,
    useValue: new NgbCustomDateParserFormatter("DD/MM/YYYY") // <== formato!
}
Enter fullscreen mode Exit fullscreen mode

Y voila, a tu manera :)

Alt Text

PD: con suerte y esto llega al siguiente release de JHipster ;)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

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

Okay