如何在 ngbdatepicker 中更改 datepicker 日期格式,如 dd/mm/yyyy

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

我正在为日期选择器使用 ng-boostrap:https://ng-bootstrap.github.io/#/components/datepicker/api 但我不知道如何更改 dd/mm/yyyy 之类的日期格式。现在显示 yyyy/mm/dd 但我想要 dd/mm/yyyy。请帮助任何人。

演示: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>

使用 ng-bootstrap 的 NgbDateISOParserFormatter as a guide,在 datepicker-popup.ts 中创建自定义格式化程序。下面的代码 (IMO) 比原始代码更直接一点,并且不依赖于导入 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 || ''}` :
        '';
  }
}

然后在datepicker-popup.module.ts中导入NgbDateCustomParserFormatter并在@NgModule中设置提供商:

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

我已经分叉了你的 StackBlitz 并添加了这个功能 here