diff --git a/src/plugin/bigIntSupport/index.js b/src/plugin/bigIntSupport/index.js new file mode 100644 index 000000000..a90bae1fe --- /dev/null +++ b/src/plugin/bigIntSupport/index.js @@ -0,0 +1,25 @@ +// eslint-disable-next-line valid-typeof +const isBigInt = num => typeof num === 'bigint' +export default (o, c, dayjs) => { + const proto = c.prototype + const parseDate = (cfg) => { + const { date } = cfg + if (isBigInt(date)) { + return Number(date) + } + return date + } + + const oldParse = proto.parse + proto.parse = function (cfg) { + cfg.date = parseDate.bind(this)(cfg) + oldParse.bind(this)(cfg) + } + + + const oldUnix = dayjs.unix + dayjs.unix = function (timestamp) { + const ts = isBigInt(timestamp) ? Number(timestamp) : timestamp + return oldUnix(ts) + } +} diff --git a/test/plugin/bigIntSupport.test.js b/test/plugin/bigIntSupport.test.js new file mode 100644 index 000000000..b2e70866f --- /dev/null +++ b/test/plugin/bigIntSupport.test.js @@ -0,0 +1,30 @@ +import MockDate from 'mockdate' +import moment from 'moment' +import dayjs from '../../src' +import bigIntSupport from '../../src/plugin/bigIntSupport' + +dayjs.extend(bigIntSupport) + +beforeEach(() => { + MockDate.set(new Date()) +}) + +afterEach(() => { + MockDate.reset() +}) + +/* global BigInt */ + +it('Parse BigInt ts and tsms', () => { + const tsms = 1666310421101 + const tsmsBig = BigInt(tsms) + const ts = 1666311003 + const tsBig = BigInt(ts) + const momentTsms = moment(tsms) + const momentTs = moment.unix(ts) + expect(dayjs(tsms).valueOf()).toBe(momentTsms.valueOf()) + expect(dayjs(tsms).valueOf()).toBe(dayjs(tsmsBig).valueOf()) + expect(dayjs.unix(ts).valueOf()).toBe(momentTs.valueOf()) + expect(dayjs.unix(tsBig).valueOf()).toBe(dayjs.unix(tsBig).valueOf()) +}) + diff --git a/types/plugin/bigIntSupport.d.ts b/types/plugin/bigIntSupport.d.ts new file mode 100644 index 000000000..d9f2f394e --- /dev/null +++ b/types/plugin/bigIntSupport.d.ts @@ -0,0 +1,11 @@ +import { PluginFunc } from 'dayjs' + +declare module 'dayjs' { + interface ConfigTypeMap { + bigIntSupport: BigInt + } + export function unix(t: BigInt): Dayjs +} + +declare const plugin: PluginFunc +export = plugin