在angular2中使用DatePipe时,我观察到的是一种奇怪的行为。出于某种原因,在通过DatePipe运行日期'03 / 09 / 1992'后,它将更改为'03 / 08 / 1992':
http://plnkr.co/edit/SK6Z9q8h7EqunmkqVtpt
(更新的代码:错误修复)
@Component({
selector: 'my-app',
template: `
<div> Invalid Date: {{ somedate | date:'MM/dd/yyyy' }}</div>
<div> DateObject: {{ dateType }}</div>
<div> DateObject With Pipe: {{ dateType | date:'MM/dd/yyyy' }}</div>
<br>
<div> Other Valid Dates </div>
<div>{{ afterdate | date:'MM/dd/yyyy' }}</div>
<div>{{ dateTypeAfter }}</div>
<div>{{ beforedate | date:'MM/dd/yyyy' }}</div>
<div>{{ dateTypeBefore }}</div>
`,
})
export class App {
somedate:string;
afterdate: string;
beforedate: string;
dateType: Date;
dateTypeAfter: Date;
dateTypeBefore: Date;
constructor() {
this.somedate = '03/09/1992';
this.afterdate = '03/09/1993';
this.beforedate = '03/09/1991';
this.dateType = new Date(this.somedate);
this.dateTypeAfter = new Date(this.afterdate);
this.dateTypeBefore = new Date(this.beforedate);
}
}
如上所示,这不会发生在1991年或1993年。结果:
Invalid Date: 03/08/1992
DateObject: Mon Mar 09 1992 00:00:00 GMT-0400 (Eastern Daylight Time)
DateObject With Pipe: 03/08/1992
Other Valid Dates
03/09/1993
Tue Mar 09 1993 00:00:00 GMT-0500 (Eastern Standard Time)
03/09/1991
Sat Mar 09 1991 00:00:00 GMT-0500 (Eastern Standard Time)
知道为什么会这样吗?还是我误解了什么?
答案 0 :(得分:0)
问题实际上是夏令时区。
Mon Mar 09 1992 00:00:00 GMT-0400 (Eastern Daylight Time)
Tue Mar 09 1993 00:00:00 GMT-0500 (Eastern Standard Time)
Sat Mar 09 1991 00:00:00 GMT-0500 (Eastern Standard Time)
请注意,GMT偏移量不同,看起来日期管道会注意到这一点。这使得03/09/1992日期实际上转换为03/08/1992 23:00:00 PM。
现在适用于我的一种可能的方法(但它有自己的问题)是使用UTC:
new Date(Date.UTC(1992, 2, 9, 5, 0, 0));
以上将确保偏移时间为5并跨时区标准化。