2

我正在为 datepicker 使用 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>
4

1 回答 1

8

使用 ng-bootstrapNgbDateISOParserFormatter 作为指南,在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 || ''}` :
        '';
  }
}

然后在in 中导入NgbDateCustomParserFormatter并设置提供程序:@NgModuledatepicker-popup.module.ts

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

我已经分叉了您的 StackBlitz 并在此处添加了此功能。

于 2020-06-01T01:02:47.783 回答