gpt4 book ai didi

angular2 ngbdatepicker 如何格式化输入字段中的日期

转载 作者:太空狗 更新时间:2023-10-29 17:06:10 26 4
gpt4 key购买 nike

我正在使用 ng-bootstrap Datepicker .我想格式化显示在模型输入字段中的日期。我查看了 API,但没有找到除 NgbDateParserFormatter 之外的任何示例不用多解释:(

在 Angular 1 中,它就像添加属性 format="MM/dd/yyyy" 一样简单。谁能帮忙?

最佳答案

"By default the datepicker comes with the basic implementation of this interface that just accepts dates in the ISO format. If you want to handle a different format (or multiple formats) you can provide your own implementation of the NgbDateParserFormatter and register it as a provider in your module." Source

this GitHub gist你可以找到一个示例实现。这是该来源的副本:

app.component.ts

import { NgbDatepickerConfig, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { NgbDateFRParserFormatter } from "./ngb-date-fr-parser-formatter"

@Component({
providers: [{provide: NgbDateParserFormatter, useClass: NgbDateFRParserFormatter}]
})
export class AppComponent {}

ngb-date-fr-parser-formatter.ts

import { Injectable } from "@angular/core";
import { NgbDateParserFormatter, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";

function padNumber(value: number) {
if (isNumber(value)) {
return `0${value}`.slice(-2);
} else {
return "";
}
}

function isNumber(value: any): boolean {
return !isNaN(toInteger(value));
}

function toInteger(value: any): number {
return parseInt(`${value}`, 10);
}


@Injectable()
export class NgbDateFRParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct {
if (value) {
const dateParts = value.trim().split('/');
if (dateParts.length === 1 && isNumber(dateParts[0])) {
return {year: toInteger(dateParts[0]), month: null, day: null};
} else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
return {year: toInteger(dateParts[1]), month: toInteger(dateParts[0]), day: null};
} else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
return {year: toInteger(dateParts[2]), month: toInteger(dateParts[1]), day: toInteger(dateParts[0])};
}
}
return null;
}

format(date: NgbDateStruct): string {
let stringDate: string = "";
if(date) {
stringDate += isNumber(date.day) ? padNumber(date.day) + "/" : "";
stringDate += isNumber(date.month) ? padNumber(date.month) + "/" : "";
stringDate += date.year;
}
return stringDate;
}
}

关于angular2 ngbdatepicker 如何格式化输入字段中的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40664523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com