【发布时间】:2020-01-10 01:46:28
【问题描述】:
我在我的 datepicker 中选择日期 May 01 1985 并将 dateOfBirth.value 发送到我的服务器,以便它可以存储在数据库中。
<mat-form-field>
<label><input #dateOfBirth matInput (blur)="_update('personal', 'dateOfBirth', dateOfBirth.value)" (click)="picker.open()" [matDatepicker]="picker" placeholder="Choose a date" formControlName="dateOfBirth" autocomplete="off" [max]="maxDate" [min]="minDate"></label>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker touchUi #picker startView="multi-year"></mat-datepicker>
<mat-error *ngIf="profileFormGroup.get('dateOfBirth').errors">Date is not valid</mat-error>
</mat-form-field>
每当我刷新页面时,所选日期应该仍然可见。
我的问题是,我选择了日期 05/01/1985,但我的日期选择器显示 4/30/1985。为什么?
private static _formatDate(timestamp: number): string {
console.log(timestamp); // Returns 483746400000
const date = new Date(+timestamp);
console.log(date.getDay()); // Returns 3 but it should be 1
return date.toISOString().substring(0, 10);
}
ngOnInit() {
this.profileService.getEntities().subscribe(data => {
this.profileFormGroup.get('dateOfBirth').patchValue(ProfileComponent._formatDate(data.dateOfBirth));
});
}
这是我在数据库中存储时间戳的方式:
private _update(tableName: string, columnName: string, theValue: any) {
// Set the correct value of dateOfBirth
console.log(theValue); // Returns 5/1/1985
if (columnName === 'dateOfBirth') {
const splitDate = theValue.split('/');
const newDate = `${splitDate[2]}/${splitDate[0]}/${splitDate[1]}`;
theValue = new Date(newDate).getTime();
console.log(theValue); // Returns 483746400000
}
const json = {
table: tableName,
column: columnName,
value: theValue
};
this.profileService.update(json).subscribe(result => {
console.log(result);
});
}
我还检查了其他示例,例如 this one on Stackblitz。如果选择日期01/05/2020,输出将是2020-04-30T22:00:00.000Z,这是错误的。
【问题讨论】:
-
为什么要除以 1000?如果将该结果保存为整数,则稍后将其乘以 1000 将不会恢复原始值;几分钟将丢失,这会将日期移至前一天。
-
你为什么要跳1000?你能提供stalkbliz链接吗?
-
@ConnorsFan 好的,现在我不再划分它,但我仍然将它乘以 1000。我仍然得到错误的日期。如果我删除
* 1000,我会收到错误 RangeError: Invalid time value -
@piyushjain 我已经更新了我的问题,你会看到一个指向 stackblitz 的链接。这不是我自己的代码,但问题可能是一样的。
-
您可以尝试
+timestamp,而不是timestamp * 1000,以避免出现异常,同时保持相同的日期/时间值。
标签: angular datepicker timestamp