dps
dps

Reputation: 864

Add a day via date-fns considering time zone change

In my project I use date-fns for date manipulations. 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. 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

Upvotes: 6

Views: 22505

Answers (2)

Vlad
Vlad

Reputation: 98

I faced with the same problem:

6 October 2019 in Australia is Daylight Saving Time Starts.

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

returns: Sat Oct 05 2019 23:00:00 GMT+1000 (Australian Eastern Standard Time)

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' )
  2. Add GMT -- dh.parse('2019-10-06 GMT' )
  3. Add +00:00 -- dh.parse('2019-10-06T00:00:00.000+00:00' )

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

Upvotes: 3

jokka
jokka

Reputation: 1912

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.

Upvotes: 1

Related Questions