I'm using the datepicker (ng-boostrap) in a popup and I would like to change the date format to dd-mm-yyyy
.
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.
UPDATE:
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") }
}
]
---
})
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…