在我的项目中,我使用date-fns进行日期操作。需要在一定范围内迭代几天。为此,我使用以下代码:
for (
// from and to are always start of some day, from <= to
let date = from;
isBefore(date, to) || isEqual(date, to);
date = addDays(date, 1)
) {
// Some operations with date
}
我希望date
总是一天的开始,但是如果时区发生变化(冬季->夏季时间),则日期会比预期的少1小时。这是一个示例:
const from = new Date('2019-03-31T00:00:00.000Z')
const fromPlusDay = dateFns.addDays(from, 1)
// I'm getting "2019-03-31T23:00:00.000Z"
// instead of "2019-04-01T00:00:00.000Z"
fromPlusDay.toISOString()
顺便说一下,我的时区是+2,到了夏令时之后变成了+3
答案 0 :(得分:0)
It is considering your time zone change and it is at the start of day (in your timezone, not UTC). Midnight in UTC is not necessarily start of day in your zone.
Check this out (I'm in GMT+1 zone):
const from = dateFns.parse('2019-03-31') // -> "2019-03-31T00:00:00.000+0100"
const fromPlusDay = dateFns.addDays(from, 1)
dateFns.format(fromPlusDay , 'YYYY-MM-DDTHH:mm:ss.SSSZZ') // -> "2019-04-01T00:00:00.000+0200"
I think what you are doing is fine, just don't expect your zone to be 00:00
in UTC, and avoid printing dates in UTC.
答案 1 :(得分:0)
我遇到了同样的问题:
2019年10月6日在澳大利亚是夏令时开始。
dh.parse('2019-10-06')
返回时间:2019年10月5日星期六23:00:00 GMT + 1000(澳大利亚东部标准时间)
解决方案正在添加有关时区(之一)的信息:
] 1)