Skip to content

Commit

Permalink
fix: update timezone plugin to support keepLocalTime (#1161)
Browse files Browse the repository at this point in the history
fix #1149
  • Loading branch information
iamkun authored Oct 23, 2020
1 parent f861aca commit 1d429e5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
13 changes: 9 additions & 4 deletions src/plugin/timezone/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { MIN, MS } from '../../constant'

const typeToPos = {
year: 0,
month: 1,
Expand All @@ -7,8 +9,6 @@ const typeToPos = {
second: 5
}

const ms = 'ms'

// Cache time-zone lookups from Intl.DateTimeFormat,
// as it is a *very* slow method.
const dtfCache = {}
Expand Down Expand Up @@ -94,10 +94,15 @@ export default (o, c, d) => {

const proto = c.prototype

proto.tz = function (timezone = defaultTimezone) {
proto.tz = function (timezone = defaultTimezone, keepLocalTime) {
const oldOffset = this.utcOffset()
const target = this.toDate().toLocaleString('en-US', { timeZone: timezone })
const diff = Math.round((this.toDate() - new Date(target)) / 1000 / 60)
const ins = d(target).$set(ms, this.$ms).utcOffset(localUtcOffset - diff, true)
let ins = d(target).$set(MS, this.$ms).utcOffset(localUtcOffset - diff, true)
if (keepLocalTime) {
const newOffset = ins.utcOffset()
ins = ins.add(oldOffset - newOffset, MIN)
}
ins.$x.$timezone = timezone
return ins
}
Expand Down
10 changes: 9 additions & 1 deletion test/plugin/timezone.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
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 utc from '../../src/plugin/utc'

dayjs.extend(utc)
dayjs.extend(timezone)
Expand Down Expand Up @@ -260,6 +260,14 @@ describe('set Default', () => {
})
})

describe('keepLocalTime', () => {
const base = dayjs.tz('2013-11-18 11:55', 'America/Toronto')
it('keepLocalTime', () => {
expect(base.tz('Europe/Berlin').format()).toBe('2013-11-18T17:55:00+01:00')
expect(base.tz('Europe/Berlin', true).format()).toBe('2013-11-18T11:55:00+01:00')
})
})

describe('Get offsetName', () => {
const dtz = dayjs.tz('2012-03-11 01:59:59', NY)
it('short', () => {
Expand Down
2 changes: 1 addition & 1 deletion types/plugin/timezone.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export = plugin

declare module 'dayjs' {
interface Dayjs {
tz(timezone?: string): Dayjs
tz(timezone?: string, keepLocalTime?: boolean): Dayjs
}

interface DayjsTimezone {
Expand Down

0 comments on commit 1d429e5

Please sign in to comment.