Am使用NgbDatePicker
问题是,每当用户点击切换并选择日期时,意味着它会同时转换所需的格式dd/mm/yyyy
,而不是选择。用户输入的日期是像ddmmyyyy
一样的字符串,它不会转换为dd/mm/yyyy
(例如:10072020到10/07/2020(,分割在CustomDateParserFormatter
中无法按预期工作。请帮助我如何解决这个问题,我不知道如何继续。component.ts
import { Injectable } from '@angular/core';
import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
@Injectable()
export class CustomDateParserFormatter {
parse(value: string): NgbDateStruct {
if (!value) {
return null;
}
const parts = value;
parts.split('/');
console.log("first calling");
return { year: +parts[0], month: +parts[1], day: +parts[2] } as NgbDateStruct;
}
format(date: NgbDateStruct): string {
// tslint:disable-next-line:prefer-template
console.log("second calling");
return date ? ('0' + date.day).slice(-2) + '/' + ('0' + date.month).slice(-2) + '/' + date.year : null;
}
}
component.html
<div class="input-group datePicker">
<input class="form-control" placeholder="DD/MM/YYYY" ngbDatepicker formControlName="dateofBrith"
[minDate]="{year: 1945, month: 1, day: 1}" [maxDate]="{year: 2020, month: 12, day: 31}"
name="dp" ngbDatepicker #d="ngbDatepicker" (ngModelChange)="changeDob($event)"
maxlength="10">
<div class="input-group-append">
<button class="btn calendar btn-custom btn-outline-secondary" (click)="d.toggle()"
type="button"><img src="/assets/images/dateicon.png"></button>
</div>
</div>
在console.log("firstcalling"(中,当用户直接输入应转换为dd/mm/yyyy
的值时,字符串拆分不起作用。你们能帮我把日期字符串ddmmyyyy
转换成日期格式dd/mm/yyy
吗。
您应该更改代码的第一件事
const parts = value;
parts.split('/');
到这个
const parts = value.split('/');
您还需要在拆分后进行检查。以下条件检查它是否包含/i。是否手动输入。
if(parts.length === 3) {
return { year: +parts[0], month: +parts[1], day: +parts[2] } as NgbDateStruct;
}
else {
return { year: +value.substring(0,2), month: +value.substring(2,4), day:
+ value.substring(4,8) } as NgbDateStruct;
}