Skip to content

Commit 1d429e5

Browse files
authored
fix: update timezone plugin to support keepLocalTime (#1161)
fix #1149
1 parent f861aca commit 1d429e5

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

src/plugin/timezone/index.js

+9-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { MIN, MS } from '../../constant'
2+
13
const typeToPos = {
24
year: 0,
35
month: 1,
@@ -7,8 +9,6 @@ const typeToPos = {
79
second: 5
810
}
911

10-
const ms = 'ms'
11-
1212
// Cache time-zone lookups from Intl.DateTimeFormat,
1313
// as it is a *very* slow method.
1414
const dtfCache = {}
@@ -94,10 +94,15 @@ export default (o, c, d) => {
9494

9595
const proto = c.prototype
9696

97-
proto.tz = function (timezone = defaultTimezone) {
97+
proto.tz = function (timezone = defaultTimezone, keepLocalTime) {
98+
const oldOffset = this.utcOffset()
9899
const target = this.toDate().toLocaleString('en-US', { timeZone: timezone })
99100
const diff = Math.round((this.toDate() - new Date(target)) / 1000 / 60)
100-
const ins = d(target).$set(ms, this.$ms).utcOffset(localUtcOffset - diff, true)
101+
let ins = d(target).$set(MS, this.$ms).utcOffset(localUtcOffset - diff, true)
102+
if (keepLocalTime) {
103+
const newOffset = ins.utcOffset()
104+
ins = ins.add(oldOffset - newOffset, MIN)
105+
}
101106
ins.$x.$timezone = timezone
102107
return ins
103108
}

test/plugin/timezone.test.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import MockDate from 'mockdate'
22
import moment from 'moment-timezone'
33
import dayjs from '../../src'
4-
import utc from '../../src/plugin/utc'
54
import timezone from '../../src/plugin/timezone'
5+
import utc from '../../src/plugin/utc'
66

77
dayjs.extend(utc)
88
dayjs.extend(timezone)
@@ -260,6 +260,14 @@ describe('set Default', () => {
260260
})
261261
})
262262

263+
describe('keepLocalTime', () => {
264+
const base = dayjs.tz('2013-11-18 11:55', 'America/Toronto')
265+
it('keepLocalTime', () => {
266+
expect(base.tz('Europe/Berlin').format()).toBe('2013-11-18T17:55:00+01:00')
267+
expect(base.tz('Europe/Berlin', true).format()).toBe('2013-11-18T11:55:00+01:00')
268+
})
269+
})
270+
263271
describe('Get offsetName', () => {
264272
const dtz = dayjs.tz('2012-03-11 01:59:59', NY)
265273
it('short', () => {

types/plugin/timezone.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export = plugin
55

66
declare module 'dayjs' {
77
interface Dayjs {
8-
tz(timezone?: string): Dayjs
8+
tz(timezone?: string, keepLocalTime?: boolean): Dayjs
99
}
1010

1111
interface DayjsTimezone {

0 commit comments

Comments
 (0)