dayjs icon indicating copy to clipboard operation
dayjs copied to clipboard

dayjs.utc returns current date when initialized with other Dayjs object

Open itamar-getloam opened this issue 3 years ago • 3 comments

Describe the bug According to the UTC plugin docs, dayjs.utc supports passing a Dayjs object as a parameter. This is also the way it's declared in the TS interfaces.

However, when passing a valid object, it initializes with the current date.

For example:

> const a = new Date("2022-05-31T21:00:00.000Z")
> const b = dayjs.utc(a);
> b.toString()
'Tue, 31 May 2022 21:00:00 GMT' // Same date as `a`, this is good
> const c = dayjs.utc(b);
> c.toString()
'Mon, 20 Jun 2022 00:00:00 GMT' // Back to current date. Not good

Expected behavior It should return an object with the same date as the one passed to it.

Information

  • Day.js Version: 1.11.2
  • OS: MacOS Monterey 12.0.1
  • Browser: NodeJS v14.19.1
  • Time zone: GMT+3

itamar-getloam avatar Jun 20 '22 15:06 itamar-getloam

Made a little test to run your code with the following configuration: Dayjs master (v1.11.3) node v16.15.0 Time zone GMT+02:00

The following test ran without problems:

import MockDate from 'mockdate'
import dayjs from '../../src'
import utc from '../../src/plugin/utc'

dayjs.extend(utc)

beforeEach(() => {
  MockDate.set(new Date())
})

afterEach(() => {
  MockDate.reset()
})

// issue 1957
describe('issue 1957', () => {
  it('dayjs.utc returns current date when initialized with other Dayjs object', () => {
    const a = new Date('2022-05-31T21:00:00.000Z')
    const b = dayjs.utc(a)
    const c = dayjs.utc(b)

    expect(a.valueOf()).toBe(b.valueOf())
    expect(a.valueOf()).toBe(c.valueOf())
  })
})

BePo65 avatar Jun 26 '22 09:06 BePo65

Hey @BePo65 , you're right! It seems the bug only occurs if you enable both utc and the objectSupport plugin. I slightly modified your test to run on my non-dev setup. This test fails for me:

import dayjs from "dayjs"

import utc from 'dayjs/plugin/utc'
dayjs.extend(utc)

import objectSupport from "dayjs/plugin/objectSupport";
dayjs.extend(objectSupport)

// issue 1957
describe('issue 1957', () => {
  it('dayjs.utc returns current date when initialized with other Dayjs object', () => {
    const a = new Date('2022-05-31T21:00:00.000Z')
    const b = dayjs.utc(a)
    const c = dayjs.utc(b)

    expect(a.valueOf()).toBe(b.valueOf())
    expect(a.valueOf()).toBe(c.valueOf())
  })
})

itamar-getloam avatar Jun 26 '22 12:06 itamar-getloam

OK, I got it: object support expects an object as first parameter that follows the structure described in the documentation.
But this collides with the constructor of dayjs that gets a dayjs object as first parameter; both have the object type.

I am working on a solution.

BePo65 avatar Jun 26 '22 15:06 BePo65