From f064c3b929949f372bcf9e15a8d32c6ceec858de Mon Sep 17 00:00:00 2001 From: iamkun Date: Wed, 21 Oct 2020 11:31:15 +0800 Subject: [PATCH] fix: update timezone plugin to support custom parse format fix #1159 --- src/plugin/timezone/index.js | 6 ++++-- test/plugin/timezone.test.js | 15 ++++++++++++++- types/plugin/timezone.d.ts | 1 + 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/plugin/timezone/index.js b/src/plugin/timezone/index.js index 3fe1bad07..c6513733a 100644 --- a/src/plugin/timezone/index.js +++ b/src/plugin/timezone/index.js @@ -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 diff --git a/test/plugin/timezone.test.js b/test/plugin/timezone.test.js index e9fb71f45..df67bdf90 100644 --- a/test/plugin/timezone.test.js +++ b/test/plugin/timezone.test.js @@ -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()) @@ -17,6 +19,7 @@ afterEach(() => { const NY = 'America/New_York' const VAN = 'America/Vancouver' +const DEN = 'America/Denver' const TOKYO = 'Asia/Tokyo' describe('Guess', () => { @@ -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) + }) +}) diff --git a/types/plugin/timezone.d.ts b/types/plugin/timezone.d.ts index 558558562..b311deb1e 100644 --- a/types/plugin/timezone.d.ts +++ b/types/plugin/timezone.d.ts @@ -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 }