Skip to content

Commit

Permalink
fixed parsing date with time zone in dayjs.tz()
Browse files Browse the repository at this point in the history
  • Loading branch information
DmytroKondratiuk committed Nov 23, 2024
1 parent 72f2aa3 commit bfc7e1f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/plugin/timezone/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ export default (o, c, d) => {
return [localTS - (Math.min(o2, o3) * 60 * 1000), Math.max(o2, o3)]
}

const hasTimeZone = (dateTimeString) => {
const timeZoneRegex = /\+\d{4}|\-\d{4}|[\+\-]\d{2}:\d{2}|UTC|GMT$|Z$/i;
return timeZoneRegex.test(dateTimeString);
};

const proto = c.prototype

proto.tz = function (timezone = defaultTimezone, keepLocalTime) {
Expand Down Expand Up @@ -136,8 +141,8 @@ export default (o, c, d) => {
const parseFormat = arg2 && arg1
const timezone = arg2 || arg1 || defaultTimezone
const previousOffset = tzOffset(+d(), timezone)
if (typeof input !== 'string') {
// timestamp number || js Date || Day.js
if ((typeof input !== 'string') || hasTimeZone(input)) {
// timestamp number || js Date || Day.js || date with time zone
return d(input).tz(timezone)
}
const localTs = d.utc(input, parseFormat).valueOf()
Expand Down
9 changes: 9 additions & 0 deletions test/plugin/timezone.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ describe('Parse', () => {
expect(newYork.valueOf()).toBe(MnewYork.valueOf())
})

it('parse target time string with timezone info', () => {
const newYork = dayjs.tz('2024-09-30 12:43:00 -0400', NY)
const DnewYork = dayjs('2024-09-30 12:43:00 -0400').tz(NY)
const MnewYork = moment('2024-09-30 12:43:00 -0400').tz(NY)
expect(newYork.format()).toBe('2024-09-30T12:43:00-04:00')
expect(newYork.format()).toBe(DnewYork.format())
expect(newYork.format()).toBe(MnewYork.format())
})

it('parse timestamp, js Date, Day.js object', () => {
const d = new Date('2020-08-07T12:00-07:00')
const result = '2020-08-07T12:00:00-07:00'
Expand Down

0 comments on commit bfc7e1f

Please sign in to comment.