Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/plugin/timezone/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { MIN, MS } from '../../constant'

const matchOffset = /Z|[+-]\d\d:?\d\d/gi

const typeToPos = {
year: 0,
month: 1,
Expand Down Expand Up @@ -135,11 +137,11 @@ export default (o, c, d) => {
d.tz = function (input, arg1, arg2) {
const parseFormat = arg2 && arg1
const timezone = arg2 || arg1 || defaultTimezone
const previousOffset = tzOffset(+d(), timezone)
if (typeof input !== 'string') {
if (typeof input !== 'string' || input.match(matchOffset)) {
// timestamp number || js Date || Day.js
return d(input).tz(timezone)
}
const previousOffset = tzOffset(+d(), timezone)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@iamkun I moved this function below the return statement. There's not reason to compute this earlier.

const localTs = d.utc(input, parseFormat).valueOf()
const [targetTs, targetOffset] = fixOffset(localTs, previousOffset, timezone)
const ins = d(targetTs).utcOffset(targetOffset)
Expand Down
12 changes: 12 additions & 0 deletions test/plugin/timezone.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ describe('Parse', () => {
const newMs = dTz.millisecond()
expect(oldMs).toEqual(newMs)
})

it('should apply the offset of the target timezone taking into consideration the timezone of the original date', () => {
const dayjs1 = dayjs.tz('2022-03-11T14:29:26.319Z', 'America/Recife')
expect(dayjs1.format()).toBe('2022-03-11T11:29:26-03:00')
const dayjs2 = dayjs.tz('2012-02-01T13:50:21.01-03:00', 'America/Recife')
expect(dayjs2.format()).toBe('2012-02-01T13:50:21-03:00')
const dayjs3 = dayjs.tz('2022-02-03T13:50:21-00:00', 'America/Recife')
expect(dayjs3.format()).toBe('2022-02-03T10:50:21-03:00')
// TODO: support rfc2822 dates
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might address this in a future pr.

// const dayjs4 = dayjs.tz('Fri, 11 Mar 2022 14:29:26 GMT', 'America/Recife')
// expect(dayjs4.format()).toBe('2022-03-11T11:29:26-03:00')
})
})

describe('Convert', () => {
Expand Down