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

Cannot read $localOffset of undefined #1540

Open
jorgestg opened this issue Jun 18, 2021 · 3 comments
Open

Cannot read $localOffset of undefined #1540

jorgestg opened this issue Jun 18, 2021 · 3 comments

Comments

@jorgestg
Copy link

jorgestg commented Jun 18, 2021

Describe the bug
Parsing a date with customParseFormat, then using utcOffset with keepLocaltime breaks diff

Running this snippet demonstrates the issue:

import dayjs from "https://cdn.skypack.dev/dayjs@1.10.5";
import utc from "https://cdn.skypack.dev/dayjs@1.10.5/plugin/utc";
import customParseFormat from "https://cdn.skypack.dev/dayjs@1.10.5/plugin/customParseFormat";

dayjs.extend(customParseFormat);
dayjs.extend(utc);

const dateTime = dayjs('2021-06-18', 'YYYY-MM-DD').utcOffset(-240, true); // No $x
const now = dayjs().utcOffset(-240);
const diff = dateTime.diff(now, 'days');
console.log('diff:', diff); // breaks
Uncaught TypeError: Cannot read property '$localOffset' of undefined
    at M2.u.valueOf (utc.js:63)
    at M2.m2.diff (dayjs.js:180)
    at M2.u.diff (utc.js:79)

Expected behavior
diff works as expected

I'm using this (really ugly) workaround in the meantime

;(day as any).$x = {}

Information

  • Day.js Version v1.10.5
  • OS: Windows
  • Browser: Edge 91.0.864.48
  • Time zone: UTC-04:00 PYT
@acerbisgianluca
Copy link

Hey, issue is still here. Did you find another solution?

@jorgestg
Copy link
Author

I ended up using this:

import dayjs, { ConfigType, OpUnitType, QUnitType } from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import utc from 'dayjs/plugin/utc'

dayjs.extend(customParseFormat)
dayjs.extend(utc)

// Work around dayjs bug
dayjs.extend(function (_, Dayjs, __) {
  const oldDiff = Dayjs.prototype.diff
  Dayjs.prototype.diff = function (
    date: ConfigType,
    unit?: QUnitType | OpUnitType,
    float?: boolean
  ): number {
    type T = dayjs.Dayjs & { $x: {} | undefined }
    const self = this as T
    const other = date as T
    self.$x ??= {}
    other.$x ??= {}
    return oldDiff.call(self, date, unit, float)
  }
})

@acerbisgianluca
Copy link

Thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants