iamkun / dayjs

⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API
https://day.js.org
MIT License
47.06k stars 2.31k forks source link

toISOString() is inconsistent with set timezone #2408

Open wang-yikai opened 1 year ago

wang-yikai commented 1 year ago

Running

const dayjsObj = dayjs('2020-01-02T15:14:59.741774+00:00').tz('America/New_York', true);
console.log(dayjsObj.toISOString());

gives inconsistent results depending on the timezone the computer is running it in. For example, a computer in the America/New_York timezone would log out 2020-01-02T15:14:59.741Z whereas a computer in UTC would log out 2020-01-02T20:14:59.741Z.

I believe this is due to the following line of code:

https://github.com/iamkun/dayjs/blob/a9d7d0398d22ebd4bfc3812ca0134a97606d54d9/src/plugin/utc/index.js#L117

For the computer in America/New_York, running new Date().getTimezoneOffset() gives 300 and for the computer in UTC, it would give 0. In both computers, dayjsObj.$offset is -300 and there is no dayjsObj.$x.$localOffset. As a result, addedOffset would be 0 for the computer in America/New_York but -300 for the computer in UTC. This addedOffset would be used to create a new Date object in which the ISO string is derived from.

Is this intended behavior or should the dayjsObj provide the same ISO string regardless of the timezone a computer is running in?

wang-yikai commented 2 months ago

Bump for more visibility