Pappa S
Pappa S

Reputation: 343

How to change datepicker date format like dd/mm/yyyy in ngbdatepicker

I am using ng-boostrap for datepicker:https://ng-bootstrap.github.io/#/components/datepicker/api But i do not know how to change date format like dd/mm/yyyy. Now it is displaying yyyy/mm/dd but i want like dd/mm/yyyy.Please help anyone.

Demo:https://stackblitz.com/edit/angular-6wpn3h-ahcq4x?file=src/app/datepicker-popup.html

  <div class="input-group">
  <input class="form-control" placeholder="dd/mm/yyyy"
         name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
  <div class="input-group-append">
    <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
  </div>
  </div>

Upvotes: 2

Views: 12641

Answers (1)

jdaz
jdaz

Reputation: 6053

Using ng-bootstrap's NgbDateISOParserFormatter as a guide, create a custom formatter in datepicker-popup.ts. The code below is (IMO) a little more straightforward than the original and doesn't rely on importing util.ts:

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

function padNumber(value: number | null) {
  if (!isNaN(value) && value !== null) {
    return `0${value}`.slice(-2);
  } else {
    return '';
  }
}

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct | null {
    if (value) {
      const dateParts = value.trim().split('/');

      let dateObj: NgbDateStruct = { day: <any>null, month: <any>null, year: <any>null }
      const dateLabels = Object.keys(dateObj);

      dateParts.forEach((datePart, idx) => {
        dateObj[dateLabels[idx]] = parseInt(datePart, 10) || <any>null;
      });
      return dateObj;
    }
    return null;
  }

  format(date: NgbDateStruct | null): string {
    return date ?
        `${padNumber(date.day)}/${padNumber(date.month)}/${date.year || ''}` :
        '';
  }
}

Then import NgbDateCustomParserFormatter and set the provider in @NgModule in datepicker-popup.module.ts:

providers: [
    {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
   ]

I've forked your StackBlitz and added this functionality here.

Upvotes: 8

Related Questions