Skip to content

Commit

Permalink
fix: update timezone plugin to support custom prase format
Browse files Browse the repository at this point in the history
fix #1159
  • Loading branch information
iamkun committed Oct 21, 2020
1 parent ee5a4ec commit 6a8632b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/plugin/timezone/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,16 @@ export default (o, c, d) => {
return result && result.value
}

d.tz = function (input, timezone = defaultTimezone) {
d.tz = function (input, arg1, arg2) {
const parseFormat = arg2 && arg1
const timezone = arg2 || arg1 || defaultTimezone
const previousOffset = tzOffset(+d(), timezone)
let localTs
if (typeof input !== 'string') {
// timestamp number || js Date || Day.js
localTs = d(input) + (previousOffset * 60 * 1000)
}
localTs = localTs || d.utc(input).valueOf()
localTs = localTs || d.utc(input, parseFormat).valueOf()
const [targetTs, targetOffset] = fixOffset(localTs, previousOffset, timezone)
const ins = d(targetTs).utcOffset(targetOffset)
ins.$x.$timezone = timezone
Expand Down
15 changes: 14 additions & 1 deletion test/plugin/timezone.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import MockDate from 'mockdate'
import moment from 'moment-timezone'
import dayjs from '../../src'
import utc from '../../src/plugin/utc'
import timezone from '../../src/plugin/timezone'
import customParseFormat from '../../src/plugin/customParseFormat'
import utc from '../../src/plugin/utc'

dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.extend(customParseFormat)

beforeEach(() => {
MockDate.set(new Date())
Expand All @@ -17,6 +19,7 @@ afterEach(() => {

const NY = 'America/New_York'
const VAN = 'America/Vancouver'
const DEN = 'America/Denver'
const TOKYO = 'Asia/Tokyo'

describe('Guess', () => {
Expand Down Expand Up @@ -273,3 +276,13 @@ describe('Get offsetName', () => {
expect(d).toBe('Eastern Standard Time')
})
})

describe('CustomPraseFormat', () => {
const result = 1602786600
it('normal', () => {
expect(dayjs.tz('2020/10/15 12:30', DEN).unix()).toBe(result)
})
it('custom', () => {
expect(dayjs.tz('10/15/2020 12:30', 'MM/DD/YYYY HH:mm', DEN).unix()).toBe(result)
})
})
1 change: 1 addition & 0 deletions types/plugin/timezone.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ declare module 'dayjs' {

interface DayjsTimezone {
(date: ConfigType, timezone?: string): Dayjs
(date: ConfigType, format: string, timezone?: string): Dayjs
guess(): string
setDefault(timezone?: string): void
}
Expand Down

0 comments on commit 6a8632b

Please sign in to comment.