我正在使用一个使用此示例的应用程序:
https://stackblitz.com/angular/rynxmynlykl
我想要以其他格式显示所选日期。我需要yyyy-mm-dd
而不是mm/dd/yyyy
。占位符很容易更改,但是我在文档(https://ng-bootstrap.github.io/#/components/datepicker/api)中找不到要查找的内容。
ngModel
接受包含年,月和日的对象。然后,Datepicker将其格式化为上述格式。
我在这里找到最接近的答案,但是现在已经过期(How to change model structure of angular powered bootstrap ngbDatepicker)。
以前有人遇到过这种情况吗?
答案 0 :(得分:4)
如the DatePicker documentation中所述,您可以提供NgbDateParserFormatter的自定义版本。有关演示,请参见this stackblitz。
解析器/格式化程序的以下代码是由this GitHubGist改编自Niels Robin-Aubertin:
import { Injectable } from "@angular/core";
import { NgbDateParserFormatter, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct {
if (value) {
const dateParts = value.trim().split('/');
if (dateParts.length === 1 && this.isNumber(dateParts[0])) {
return { year: this.toInteger(dateParts[0]), month: null, day: null };
} else if (dateParts.length === 2 && this.isNumber(dateParts[0]) && this.isNumber(dateParts[1])) {
return { year: this.toInteger(dateParts[1]), month: this.toInteger(dateParts[0]), day: null };
} else if (dateParts.length === 3 && this.isNumber(dateParts[0]) && this.isNumber(dateParts[1]) && this.isNumber(dateParts[2])) {
return { year: this.toInteger(dateParts[2]), month: this.toInteger(dateParts[0]), day: this.toInteger(dateParts[1]) };
}
}
return null;
}
format(date: NgbDateStruct): string {
let stringDate: string = "";
if (date) {
stringDate += this.isNumber(date.month) ? this.padNumber(date.month) + "/" : "";
stringDate += this.isNumber(date.day) ? this.padNumber(date.day) + "/" : "";
stringDate += date.year;
}
return stringDate;
}
private padNumber(value: number) {
if (this.isNumber(value)) {
return `0${value}`.slice(-2);
} else {
return "";
}
}
private isNumber(value: any): boolean {
return !isNaN(this.toInteger(value));
}
private toInteger(value: any): number {
return parseInt(`${value}`, 10);
}
}
日期解析器/格式器已添加到模块中的提供程序:
import { NgbDateParserFormatter, ... } from '@ng-bootstrap/ng-bootstrap';
import { CustomDateParserFormatter } from "./datepicker-formatter";
@NgModule({
...
providers: [{ provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter }]
})
export class AppModule { }