Skip to content

Commit f6dce48

Browse files
authored
fix: add BigIntSupport plugin (#2087)
1 parent 7ae1a1d commit f6dce48

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

src/plugin/bigIntSupport/index.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// eslint-disable-next-line valid-typeof
2+
const isBigInt = num => typeof num === 'bigint'
3+
export default (o, c, dayjs) => {
4+
const proto = c.prototype
5+
const parseDate = (cfg) => {
6+
const { date } = cfg
7+
if (isBigInt(date)) {
8+
return Number(date)
9+
}
10+
return date
11+
}
12+
13+
const oldParse = proto.parse
14+
proto.parse = function (cfg) {
15+
cfg.date = parseDate.bind(this)(cfg)
16+
oldParse.bind(this)(cfg)
17+
}
18+
19+
20+
const oldUnix = dayjs.unix
21+
dayjs.unix = function (timestamp) {
22+
const ts = isBigInt(timestamp) ? Number(timestamp) : timestamp
23+
return oldUnix(ts)
24+
}
25+
}

test/plugin/bigIntSupport.test.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import MockDate from 'mockdate'
2+
import moment from 'moment'
3+
import dayjs from '../../src'
4+
import bigIntSupport from '../../src/plugin/bigIntSupport'
5+
6+
dayjs.extend(bigIntSupport)
7+
8+
beforeEach(() => {
9+
MockDate.set(new Date())
10+
})
11+
12+
afterEach(() => {
13+
MockDate.reset()
14+
})
15+
16+
/* global BigInt */
17+
18+
it('Parse BigInt ts and tsms', () => {
19+
const tsms = 1666310421101
20+
const tsmsBig = BigInt(tsms)
21+
const ts = 1666311003
22+
const tsBig = BigInt(ts)
23+
const momentTsms = moment(tsms)
24+
const momentTs = moment.unix(ts)
25+
expect(dayjs(tsms).valueOf()).toBe(momentTsms.valueOf())
26+
expect(dayjs(tsms).valueOf()).toBe(dayjs(tsmsBig).valueOf())
27+
expect(dayjs.unix(ts).valueOf()).toBe(momentTs.valueOf())
28+
expect(dayjs.unix(tsBig).valueOf()).toBe(dayjs.unix(tsBig).valueOf())
29+
})
30+

types/plugin/bigIntSupport.d.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { PluginFunc } from 'dayjs'
2+
3+
declare module 'dayjs' {
4+
interface ConfigTypeMap {
5+
bigIntSupport: BigInt
6+
}
7+
export function unix(t: BigInt): Dayjs
8+
}
9+
10+
declare const plugin: PluginFunc
11+
export = plugin

0 commit comments

Comments
 (0)