我正在使用 Angular Material Beta 11 版本开发 Angular 应用程序 (v4.4.3)。在 beta 11 中,日期选择器接受 ISO 格式字符串中的日期。但是,在我的应用程序中,日期选择器模块中的日期关闭 1 天,如下图所示:
我的应用程序中的日期流程如下,该应用程序从 Mysql 数据库接收一个 Unix 纪元时间的日期,我将该纪元时间日期转换为 ISOString 字符串格式,并将该 ISO 日期返回给 matDatePicker。
/**
* This method takes the key, which is a epoch time in string format and convert into JS Date object.
* @param key {string} - the epoch time
* @return {string} - Date Object.
*/
private static dateHelper(key: string): any {
const dateObj = new Date(+key * 1000);
// Need to return ISOString format date as accepted by Material DatePicker component
return dateObj.toISOString().substring(0, 10);
}
我还有日期选择器模块,以自定义格式显示日期:
import {NgModule} from '@angular/core';
import {MdDatepickerModule, MdNativeDateModule, NativeDateAdapter, DateAdapter, MD_DATE_FORMATS} from '@angular/material';
// extend NativeDateAdapter's format method to specify the date format.
export class CustomDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getUTCDate();
const month = date.getUTCMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
} else {
return date.toDateString();
}
}
}
const MY_DATE_FORMATS = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};
@NgModule({
declarations: [],
imports: [],
exports: [MdDatepickerModule, MdNativeDateModule],
providers: [
{
provide: DateAdapter, useClass: CustomDateAdapter
},
{
provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS
}
]
})
export class DatePickerModule {
}
日期选择器:
<mat-form-field>
<input matInput
[matDatepicker]="myDate"
placeholder="Start Date"
[(ngModel)]="date"
name="start_date" required>
<mat-datepicker-toggle matSuffix [for]="myDate"></mat-datepicker-toggle>
<mat-datepicker #myDate></mat-datepicker>
<mat-error>This field is required!</mat-error>
</mat-form-field>
我用谷歌搜索了一下,有一些关于这个问题的帖子,但我没能完全理解它们。对此的任何输入将不胜感激。谢谢!
最佳答案
如果你使用 date.getDate()
和 date.getMonth()
它应该可以工作,不 date.getUTCDate( )
和 date.getUTCMonth()
,在自定义日期适配器的 format
方法中。
试着让我们知道:
export class CustomDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat == "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return `${year}-${month}-${day}`
} else {
return date.toDateString();
}
}
}
关于javascript - Angular Material 2 (MatDatepickerModule) - 在日期选择器中选择的日期偏移 1 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435195/