Skip to content

Commit

Permalink
fix: Fix CustomParseFormat plugin of parsing only YYYY / YYYY-MM bug
Browse files Browse the repository at this point in the history
fix #849
  • Loading branch information
iamkun committed Apr 17, 2020
1 parent 62b092d commit d2de5b0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/plugin/customParseFormat/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,21 +151,20 @@ const parseFormattedInput = (input, format, utc) => {
const {
year, month, day, hours, minutes, seconds, milliseconds, zone
} = parser(input)
if (zone) {
return new Date(Date.UTC(
year, month - 1, day,
hours || 0,
minutes || 0, seconds || 0, milliseconds || 0
) + (zone.offset * 60 * 1000))
}
const now = new Date()
const d = day || ((!year && !month) ? now.getDate() : 1)
const y = year || now.getFullYear()
const M = month > 0 ? month - 1 : now.getMonth()
let M = 0
if (!(year && !month)) {
M = month > 0 ? month - 1 : now.getMonth()
}
const h = hours || 0
const m = minutes || 0
const s = seconds || 0
const ms = milliseconds || 0
if (zone) {
return new Date(Date.UTC(y, M, d, h, m, s, ms + (zone.offset * 60 * 1000)))
}
if (utc) {
return new Date(Date.UTC(y, M, d, h, m, s, ms))
}
Expand Down
19 changes: 19 additions & 0 deletions test/plugin/customParseFormat.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,25 @@ it('parse HH:mm:ss but only one digit', () => {
expect(dayjs(input, format).valueOf()).toBe(moment(input, format).valueOf())
})

describe('parse YYYY / YYYY-MM only', () => {
it('YYYY', () => {
const input = '2001 +08:00'
const format = 'YYYY Z'
expect(dayjs(input, format).valueOf()).toBe(moment(input, format).valueOf())
const input2 = '2001'
const format2 = 'YYYY'
expect(dayjs(input2, format2).valueOf()).toBe(moment(input2, format2).valueOf())
})
it('YYYY-MM', () => {
const input = '2001-01 +08:00'
const format = 'YYYY-MM Z'
expect(dayjs(input, format).valueOf()).toBe(moment(input, format).valueOf())
const input2 = '2001-01'
const format2 = 'YYYY-MM'
expect(dayjs(input2, format2).valueOf()).toBe(moment(input2, format2).valueOf())
})
})

it('parse hh:mm:ss but only one digit', () => {
const input = '0:0:1'
const format = 'hh:mm:ss'
Expand Down

0 comments on commit d2de5b0

Please sign in to comment.