Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: update UTC plugin to support keepLocalTime #973

Merged
merged 2 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/plugin/utc/index.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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