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

标签 typescript angular8 ngb-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>

最佳答案

使用 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 || ''}` :
        '';
  }
}

然后导入NgbDateCustomParserFormatter并在datepicker-popup.module.ts中的@NgModule中设置provider:

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

我已经 fork 了您的 StackBlitz 并添加了此功能 here .

关于typescript - 如何在 ngbdatepicker 中更改 datepicker 日期格式,如 dd/mm/yyyy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119447/

相关文章:

javascript - JS 或 TS - 获取接口(interface)的键

typescript - Mixin 作为 TypeScript 中的类装饰器不会更新类属性

javascript - Typescript 4.4 打破元组联合推理

javascript - TypeScript:如何在字符串数组上使用 Array.includes 可能未定义的值(可选链接)

javascript - 更改后 Angular 8 值不会在 View 中更新

javascript - fontawesome onclick 图标使用 Material 表更改 Angular

angular - 如何在angular bootstrap的ngbDatepicker输入字段中更改日期格式?

angular - NullInjectorError : No provider for HighContrastModeDetector

javascript - 如何将 NgbDate 转换为 js Date 对象?