所以我要做的是创建一个月的数组。但是,当我把月份添加到我的月份数组中时,我得到
“一月”、“二月”、“三月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十二月”
结果。但在我加入数组之前,几个月都可以打印出来。
注意,四月和十一月都在“原始”产出中。我检查过这个类似的问题和其他人,但它们并不像我想象的那样相似。除了3月2日的那一期。
如果重要的话,我使用的是Chrome版本59.0.3071.115 (官方版本)(64位)
这是我的代码:
getMonths(form: string = 'long'): string[] {
if (form.toLowerCase() !== 'long' || form.toLowerCase() !== 'short') {
form = 'long';
}
if (!this.yearSelected) { // sets default year to today
this.yearSelected = this.today.getFullYear();
}
let months: string[] = [];
let locale: string = "en-US";
let month: Date;
// console.log(this.selectedYear);
for (let i = 0; i < 12; i++) {
month = new Date(this.yearSelected, i, 1);
console.log(month);
months.push(month.toLocaleString(locale, { month: form }));
console.log(months[i]); // <-getting odd output from here
}
return months;
}在for循环中,我根据我提供的链接将1添加到'day‘参数中。但我最初的代码是
month = new Date(this.yearSelected, i);如果重要的话。我还在for循环的末尾对有问题的输出进行了注释(用于指示)。
编辑:刚更新到Chrome 60.0.3112.78
编辑:已删除的输入错误toLocalLowerCase -> toLowercase()
编辑:所以这个问题与夏令时有关。由于James的建议,我添加了15 to月份=新日期(this.yearSelected,i),因此现在是月份=新日期(this.yearSelected,i,15)。我将研究如何使用UTC日期- Mozilla链接
发布于 2017-08-01 19:15:45
您在不同的时区,日期转换为当地时间,这是正确的,1917年4月1日太阳的美国东部时间,转换为东部时间,是3月31日23:00:00,因此你得到三月,三月。
这是一个纯粹的TypeScript问题,以及TypeScript是如何转换回JavaScript的,TypeScript与UTCString而不是LocaleTimeString有相同的问题。
getMonths(form: string = 'long'): string[] {
if (form.toLowerCase() !== 'long' || form.toLowerCase() !== 'short') {
form = 'long';
}
if (!this.yearSelected) { // sets default year to today
this.yearSelected = this.today.getFullYear();
}
let months: string[] = [];
let locale: string = "en-US";
let month: Date;
// console.log(this.selectedYear);
for (let i = 0; i < 12; i++) {
month = new Date(this.yearSelected, i);
console.log(month);
months.push(month.toUTCString(locale, { month: form }));
console.log(months[i]); // <-getting odd output from here
}
return months;
}返回:预期的["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
发布于 2017-08-01 19:50:17
正如Brian和James提到的,这是一个夏时制问题。我采纳了詹姆斯的建议并补充说
month = new Date(this.yearSelected, i, 15); // 15 to avoid daylight savings time issues解决了这个问题。我还发现,我可以在js中使用UTC日期,我将对其进行研究。谢谢。
https://stackoverflow.com/questions/45445670
复制相似问题