dayjs
dayjs copied to clipboard
utcOffset returns wrong result when called on an instance that already has a fixed offset
Describe the bug
When calling .utcOffset() on a dayjs instance that has already had its offset set with .utcOffset(), the wrong result is returned.
For example, I create a dayjs instance in my local time of +10:00, and set its offset to +08:00:
dayjs("2023-08-24T19:52:00").utcOffset(480).format()
"2023-08-24T17:52:00+08:00"
So far, so good. Now I want to convert that same time back to +10:00. It should be 19:52:00+10:00, but instead I get this:
dayjs("2023-08-24T19:52:00").utcOffset(480).utcOffset(600).format()
"2023-08-24T21:52:00+10:00"
So it has changed the underlying time by +2 hours, as well as setting the offset? Weird.
But if I transition it through .utcOffset(0), I get the right result:
dayjs("2023-08-24T19:52:00").utcOffset(480).utcOffset(0).utcOffset(600).format()
"2023-08-24T19:52:00+10:00"
Expected behavior
I expect that .utcOffset() with no second argument should not change the underlying time. It should work the same way when called on an instance that has an offset set, as it does when called on a normal instance, and it should follow the documented behaviour in all cases.
Information
- Day.js Version: not sure, whatever version is provided in the browser console on https://day.js.org/docs/en/manipulate/utc-offset
- OS: MacOS
- Browser: FF 116.0.3
- Time zone: UTC+10:00 Australia/Canberra
I ran into the same issue today. I'd expect that it shouldn't matter how much times utcOffset()
is applied, the resulting time should always be correct, given the last specified offset. Now it's like this:
dayjs('2023-01-30T13:00:00.000Z').utcOffset(0).format()
//'2023-01-30T13:00:00Z' - correct
dayjs('2023-01-30T13:00:00.000Z').utcOffset(1).format()
//'2023-01-30T14:00:00+01:00' - correct
dayjs('2023-01-30T13:00:00.000Z').utcOffset(-1).format()
//'2023-01-30T12:00:00-01:00' - correct
dayjs('2023-01-30T13:00:00.000Z').utcOffset(1).utcOffset(-1).format()
//'2023-01-30T16:00:00-01:00' - incorrect
Seen on StackOverflow also. https://stackoverflow.com/questions/78662534/dayjs-wrong-timezone-conversion
Seen on StackOverflow also. https://stackoverflow.com/questions/78662534/dayjs-wrong-timezone-conversion
It was me, to fix this, I just create another instance for each conversion I need like
const toUtc = dayjs(date).utcOffset(0)
const toMinusThreeTime = dayjs(toUtc.format()).utcOffset(-180).