简体   繁体   English

考虑到时区变化,通过 date-fns 添加一天

[英]Add a day via date-fns considering time zone change

In my project I use date-fns for date manipulations.在我的项目中,我使用 date-fns 进行日期操作。 There is a need to iterate days in some range.需要在某个范围内迭代天数。 For that I'm using following code:为此,我使用以下代码:

  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
  }

I'm expecting date to always be the start of some day, but in case timezone changes (winter time -> summer time), date is 1 hour less then expected.我希望date始终是某一天的开始,但如果时区发生变化(冬季时间 - > 夏季时间),日期会比预期少 1 小时。 Here is an example:下面是一个例子:

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()

By the way my time zone was +2 and after moving to summer time it became +3顺便说一句,我的时区是 +2,在移到夏令时后变成了 +3

I faced with the same problem:我遇到了同样的问题:

6 October 2019 in Australia is Daylight Saving Time Starts. 2019 年 10 月 6 日在澳大利亚是夏令时开始。

dh.parse('2019-10-06')

returns: Sat Oct 05 2019 23:00:00 GMT+1000 (Australian Eastern Standard Time)返回:2019 年 10 月 5 日星期六 23:00:00 GMT+1000(澳大利亚东部标准时间)

Solution is adding info about time zone (one of):解决方案是添加有关时区的信息(其中之一):

  1. Add sign of absent time zone offset “Z” -- dh.parse('2019-10-06T00:00:00.000Z' )添加不存在时区偏移量“Z”的符号——dh.parse('2019-10-06T00:00:00.000Z')
  2. Add GMT -- dh.parse('2019-10-06 GMT' )添加 GMT -- dh.parse('2019-10-06 GMT')
  3. Add +00:00 -- dh.parse('2019-10-06T00:00:00.000+00:00' )添加 +00:00 -- dh.parse('2019-10-06T00:00:00.000+00:00' )

示例]([![https://i.imgur.com/fvLWQQO.png ] 1 ) ] 1 )

It is considering your time zone change and it i s at the start of day (in your timezone, not UTC). 正在考虑您的时区变化和它I S在一天的开始(在你的时区,而不是UTC)。 Midnight in UTC is not necessarily start of day in your zone. UTC中的午夜不一定是您所在区域的一天开始。

Check this out (I'm in GMT+1 zone): 看看这个(我在GMT + 1区):

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. 我认为你正在做的很好,只是不要指望你的区域是UTC的00:00 ,并避免以UTC格式打印日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM