实现自定义NgbDateParserFormatter来更改NgbInputDatepicker上输入值的格式是否正确? [英] Is it correct to implement a custom NgbDateParserFormatter to change the format of the input value on NgbInputDatepicker?
问题描述
我正在使用日期选择器( ng-boostrap )弹出窗口,我想将日期格式更改为dd-mm-yyyy
.
I'm using the datepicker (ng-boostrap) in a popup and I would like to change the date format to dd-mm-yyyy
.
似乎可以通过实现新的NgbDateParserFormatter
来替换默认的NgbDateISOParserFormatter
来解决.
It seems that it can be solved by implementing a new NgbDateParserFormatter
to replace the default NgbDateISOParserFormatter
.
但是我想知道是否还有另一种方式.
But I was wondering if there is another way.
更新:
使用Moment.js的NgbDateParserFormatter
的小实现
(已使用ng-bootstrap的1.0.0-alpha.14版本进行测试):
A small implementation of NgbDateParserFormatter
using Moment.js
(tested with version 1.0.0-alpha.14 of ng-bootstrap):
import {NgbDateParserFormatter, NgbDateStruct} from '@ng-bootstrap/ng-bootstrap';
import * as moment from 'moment';
export class NgbDateMomentParserFormatter extends NgbDateParserFormatter {
constructor(private momentFormat: string) {
super();
};
format(date: NgbDateStruct): string {
if (date === null) {
return '';
}
let d = moment({ year: date.year,
month: date.month - 1,
date: date.day });
return d.isValid() ? d.format(this.momentFormat) : '';
}
parse(value: string): NgbDateStruct {
if (!value) {
return null;
}
let d = moment(value, this.momentFormat);
return d.isValid() ? { year: d.year(),
month: d.month() + 1,
day: d.date() } : null;
}
}
在模块中,您使用工厂将提供程序包括在内,以指示日期格式作为参数:
And in a module, you include the provider using a factory to indicate the date format as a parameter:
---
@NgModule({
---
providers: [
{
provide: NgbDateParserFormatter,
useFactory: () => { return new NgbDateMomentParserFormatter("DD-MM-YYYY") }
}
]
---
})
推荐答案
到目前为止,实现自定义NgbDateParserFormatter
是最好的方法.是的,这是正确的方法.
As of today implementing a custom NgbDateParserFormatter
is the best way to go. So yes, it is a correct way.
将来,我们可能会更复杂地实现NgbDateParserFormatter
,您将可以只传递所需的格式(例如yyyy-MM-dd
).添加此功能将取决于用户的兴趣.
In the future we might have a more sophisticated implementation of the NgbDateParserFormatter
where you will be able to just pass a desired format (ex. yyyy-MM-dd
). Adding this feature will depend on user's interest.
您还可以在 https:/中查看更多背景信息/github.com/ng-bootstrap/ng-bootstrap/issues/754#issuecomment-247767027
这篇关于实现自定义NgbDateParserFormatter来更改NgbInputDatepicker上输入值的格式是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!