Skip to content

Commit 48cbf31

Browse files
authored
fix: update timezone plugin to support custom parse format (#1160)
fix #1159
1 parent 1d429e5 commit 48cbf31

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

src/plugin/timezone/index.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -114,14 +114,16 @@ export default (o, c, d) => {
114114
return result && result.value
115115
}
116116

117-
d.tz = function (input, timezone = defaultTimezone) {
117+
d.tz = function (input, arg1, arg2) {
118+
const parseFormat = arg2 && arg1
119+
const timezone = arg2 || arg1 || defaultTimezone
118120
const previousOffset = tzOffset(+d(), timezone)
119121
let localTs
120122
if (typeof input !== 'string') {
121123
// timestamp number || js Date || Day.js
122124
localTs = d(input) + (previousOffset * 60 * 1000)
123125
}
124-
localTs = localTs || d.utc(input).valueOf()
126+
localTs = localTs || d.utc(input, parseFormat).valueOf()
125127
const [targetTs, targetOffset] = fixOffset(localTs, previousOffset, timezone)
126128
const ins = d(targetTs).utcOffset(targetOffset)
127129
ins.$x.$timezone = timezone

test/plugin/timezone.test.js

+13
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ import MockDate from 'mockdate'
22
import moment from 'moment-timezone'
33
import dayjs from '../../src'
44
import timezone from '../../src/plugin/timezone'
5+
import customParseFormat from '../../src/plugin/customParseFormat'
56
import utc from '../../src/plugin/utc'
67

78
dayjs.extend(utc)
89
dayjs.extend(timezone)
10+
dayjs.extend(customParseFormat)
911

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

1820
const NY = 'America/New_York'
1921
const VAN = 'America/Vancouver'
22+
const DEN = 'America/Denver'
2023
const TOKYO = 'Asia/Tokyo'
2124

2225
describe('Guess', () => {
@@ -281,3 +284,13 @@ describe('Get offsetName', () => {
281284
expect(d).toBe('Eastern Standard Time')
282285
})
283286
})
287+
288+
describe('CustomPraseFormat', () => {
289+
const result = 1602786600
290+
it('normal', () => {
291+
expect(dayjs.tz('2020/10/15 12:30', DEN).unix()).toBe(result)
292+
})
293+
it('custom', () => {
294+
expect(dayjs.tz('10/15/2020 12:30', 'MM/DD/YYYY HH:mm', DEN).unix()).toBe(result)
295+
})
296+
})

types/plugin/timezone.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ declare module 'dayjs' {
1010

1111
interface DayjsTimezone {
1212
(date: ConfigType, timezone?: string): Dayjs
13+
(date: ConfigType, format: string, timezone?: string): Dayjs
1314
guess(): string
1415
setDefault(timezone?: string): void
1516
}

0 commit comments

Comments
 (0)