Skip to content

Commit b0dda31

Browse files
authored
fix: update devHelper add warning "passing Year as a Number will be parsed as a Unix timestamp" (#1315)
1 parent 824dcb8 commit b0dda31

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/plugin/devHelper/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ export default (o, c, d) => {
88
if (typeof date === 'string' && date.length === 13) {
99
console.warn(`To parse a Unix timestamp like ${date}, you should pass it as a Number. https://day.js.org/docs/en/parse/unix-timestamp-milliseconds`)
1010
}
11+
if (typeof date === 'number' && String(date).length === 4) {
12+
console.warn(`Guessing you may want to parse the Year ${date}, you should pass it as a String ${date}, not a Number. Otherwise, ${date} will be treated as a Unix timestamp`)
13+
}
1114
if (cfg.args.length >= 2 && !d.p.customParseFormat) {
1215
console.warn(`To parse a date-time string like ${date} using the given format, you should enable customParseFormat plugin first. https://day.js.org/docs/en/parse/string-format`)
1316
}

test/plugin/devHelper.test.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import MockDate from 'mockdate'
2+
import dayjs from '../../src'
3+
import devHelper from '../../src/plugin/devHelper'
4+
5+
dayjs.extend(devHelper)
6+
7+
beforeEach(() => {
8+
MockDate.set(new Date())
9+
})
10+
11+
afterEach(() => {
12+
MockDate.reset()
13+
})
14+
15+
global.console.warn = jest.genMockFunction()
16+
17+
18+
it('Warning: passing Year as a Number will be parsed as a Unix timestamp', () => {
19+
const consoleSpy = jest.spyOn(console, 'warn')
20+
dayjs(2020)
21+
expect(consoleSpy).toHaveBeenCalledWith('Guessing you may want to parse the Year 2020, you should pass it as a String 2020, not a Number. Otherwise, 2020 will be treated as a Unix timestamp')
22+
})
23+
24+
it('Warning Passing Unix timestamp as a String not Number', () => {
25+
const consoleSpy = jest.spyOn(console, 'warn')
26+
dayjs('1231231231231')
27+
expect(consoleSpy).toHaveBeenCalledWith('To parse a Unix timestamp like 1231231231231, you should pass it as a Number. https://day.js.org/docs/en/parse/unix-timestamp-milliseconds')
28+
})
29+
30+
it('Warning Enable customParseFormat plugin while passing the second format parameter', () => {
31+
const consoleSpy = jest.spyOn(console, 'warn')
32+
dayjs('2020', 'YYYY')
33+
expect(consoleSpy).toHaveBeenCalledWith('To parse a date-time string like 2020 using the given format, you should enable customParseFormat plugin first. https://day.js.org/docs/en/parse/string-format')
34+
})

0 commit comments

Comments
 (0)