Skip to content

Commit

Permalink
fix: update timezone plugin to support custom parse format (#1160)
Browse files Browse the repository at this point in the history
fix #1159
  • Loading branch information
iamkun authored Oct 23, 2020
1 parent 1d429e5 commit 48cbf31
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/plugin/timezone/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,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
13 changes: 13 additions & 0 deletions test/plugin/timezone.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import MockDate from 'mockdate'
import moment from 'moment-timezone'
import dayjs from '../../src'
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 @@ -281,3 +284,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 48cbf31

Please sign in to comment.