Skip to content

Commit

Permalink
fix: Update UTC plugin to support keepLocalTime (#973)
Browse files Browse the repository at this point in the history
  • Loading branch information
iamkun committed Jul 29, 2020
1 parent 70c1239 commit 9f488e5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/plugin/utc/index.js
Expand Up @@ -45,7 +45,7 @@ export default (option, Dayjs, dayjs) => {
}

const oldUtcOffset = proto.utcOffset
proto.utcOffset = function (input) {
proto.utcOffset = function (input, keepLocalTime) {
const { u } = this.$utils()
if (u(input)) {
if (this.$u) {
Expand All @@ -57,7 +57,12 @@ export default (option, Dayjs, dayjs) => {
return oldUtcOffset.call(this)
}
const offset = Math.abs(input) <= 16 ? input * 60 : input
let ins
let ins = this
if (keepLocalTime) {
ins.$offset = offset
ins.$u = input === 0
return ins
}
if (input !== 0) {
ins = this.local().add(offset + localOffset, MIN)
ins.$offset = offset
Expand Down
17 changes: 17 additions & 0 deletions test/plugin/utc-utcOffset.test.js
Expand Up @@ -58,6 +58,23 @@ it('utcOffset(0) enable utc mode', () => {
expect(dayjs().utcOffset(0).isUTC()).toBeTruthy()
})

it('utcOffset keepLocalTime', () => {
const d = '2000-01-01T06:00:00Z'
expect(dayjs.utc(d).utcOffset(5, true).format())
.toBe(moment.utc(d).utcOffset(5, true).format())
expect(dayjs.utc(d).utcOffset(0, true).format())
.toBe(moment.utc(d).utcOffset(0, true).format())
expect(dayjs.utc(d).utcOffset(-5, true).format())
.toBe(moment.utc(d).utcOffset(-5, true).format())
const d2 = '2016-01-01 00:00:00'
expect(dayjs(d2).utcOffset(0, true).format())
.toBe(moment(d2).utcOffset(0, true).format())
expect(dayjs(d2).utcOffset(-5, true).format())
.toBe(moment(d2).utcOffset(-5, true).format())
expect(dayjs(d2).utcOffset(5, true).format())
.toBe(moment(d2).utcOffset(5, true).format())
})

test('UTC mode', () => {
const d = dayjs.utc('2000-01-01T06:00:00Z')
expect(d.isUTC()).toBeTruthy()
Expand Down
2 changes: 1 addition & 1 deletion types/plugin/utc.d.ts
Expand Up @@ -12,7 +12,7 @@ declare module 'dayjs' {

isUTC(): boolean

utcOffset(offset: number): Dayjs
utcOffset(offset: number, keepLocalTime?: boolean): Dayjs
}

export function utc(config?: ConfigType, format?: string): Dayjs
Expand Down

0 comments on commit 9f488e5

Please sign in to comment.