Skip to content

Commit 3d73543

Browse files
authored
fix: fix DST bug in utc plugin (#1053)
1 parent 94af9af commit 3d73543

3 files changed

Lines changed: 17 additions & 5 deletions

File tree

src/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as C from './constant'
2-
import U from './utils'
32
import en from './locale/en'
3+
import U from './utils'
44

55
let L = 'en' // global locale
66
const Ls = {} // global loaded locale
@@ -43,6 +43,7 @@ const wrapper = (date, instance) =>
4343
dayjs(date, {
4444
locale: instance.$L,
4545
utc: instance.$u,
46+
x: instance.$x,
4647
$offset: instance.$offset // todo: refactor; do not use this.$offset in you code
4748
})
4849

@@ -81,6 +82,7 @@ class Dayjs {
8182

8283
parse(cfg) {
8384
this.$d = parseDate(cfg)
85+
this.$x = cfg.x || {}
8486
this.init()
8587
}
8688

src/plugin/utc/index.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { MILLISECONDS_A_MINUTE, MIN } from '../../constant'
22

33
export default (option, Dayjs, dayjs) => {
4-
const localOffset = (new Date()).getTimezoneOffset()
54
const proto = Dayjs.prototype
65
dayjs.utc = function (date) {
76
const cfg = { date, utc: true, args: arguments } // eslint-disable-line prefer-rest-params
@@ -64,8 +63,11 @@ export default (option, Dayjs, dayjs) => {
6463
return ins
6564
}
6665
if (input !== 0) {
67-
ins = this.local().add(offset + localOffset, MIN)
66+
const localTimezoneOffset = this.$u
67+
? this.toDate().getTimezoneOffset() : -1 * this.utcOffset()
68+
ins = this.local().add(offset + localTimezoneOffset, MIN)
6869
ins.$offset = offset
70+
ins.$x.$localOffset = localTimezoneOffset
6971
} else {
7072
ins = this.utc()
7173
}
@@ -81,7 +83,7 @@ export default (option, Dayjs, dayjs) => {
8183

8284
proto.valueOf = function () {
8385
const addedOffset = !this.$utils().u(this.$offset)
84-
? this.$offset + localOffset : 0
86+
? this.$offset + (this.$x.$localOffset || (new Date()).getTimezoneOffset()) : 0
8587
return this.$d.valueOf() - (addedOffset * MILLISECONDS_A_MINUTE)
8688
}
8789

test/timezone.test.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import moment from 'moment'
21
import MockDate from 'mockdate'
2+
import moment from 'moment'
33
import dayjs from '../src'
44
import utc from '../src/plugin/utc'
55

@@ -54,3 +54,11 @@ it('UTC add day in DST', () => {
5454
.toBe(momentTest.clone().add(2, 'day').format())
5555
})
5656

57+
it('UTC and utcOffset', () => {
58+
const test1 = 1331449199000 // 2012/3/11 14:59:59
59+
expect(moment(test1).utcOffset(-300).format())
60+
.toBe(dayjs(test1).utcOffset(-300).format())
61+
const test2 = '2000-01-01T06:31:00Z'
62+
expect(moment.utc(test2).utcOffset(-60).format())
63+
.toBe(dayjs.utc(test2).utcOffset(-60).format())
64+
})

0 commit comments

Comments
 (0)