Skip to content

Commit

Permalink
fix: CustomParseFormat plugin parse Do format string
Browse files Browse the repository at this point in the history
fix #522
  • Loading branch information
iamkun committed Mar 10, 2019
1 parent 1768305 commit bf27fda
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/plugin/customParseFormat/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const formattingTokens = /(\[[^[]*\])|([-:/.()\s]+)|(A|a|YYYY|YY?|MM?M?M?|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g
const formattingTokens = /(\[[^[]*\])|([-:/.()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g

const match1 = /\d/ // 0 - 9
const match2 = /\d\d/ // 00 - 99
Expand Down Expand Up @@ -56,6 +56,16 @@ const expressions = {
hh: [match1to2, addInput('hours')],
D: [match1to2, addInput('day')],
DD: [match2, addInput('day')],
Do: [matchWord, function (input) {
const { ordinal } = locale;
[this.day] = input.match(/\d+/)
if (!ordinal) return
for (let i = 1; i <= 31; i += 1) {
if (ordinal(i).replace(/\[|\]/g, '') === input) {
this.day = i
}
}
}],
M: [match1to2, addInput('month')],
MM: [match2, addInput('month')],
MMM: [matchWord, function (input) {
Expand Down
17 changes: 17 additions & 0 deletions test/plugin/customParseFormat.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import moment from 'moment'
import dayjs from '../../src'
import customParseFormat from '../../src/plugin/customParseFormat'
import uk from '../../src/locale/uk'
import '../../src/locale/zh-cn'

dayjs.extend(customParseFormat)

Expand Down Expand Up @@ -169,3 +170,19 @@ it('correctly parse month from string after changing locale globally', () => {
moment.locale(momentLocale)
}
})

it('correctly parse ordinal', () => {
const input = '7th March 2019'
const input2 = '17th March 2019'
const inputFalse = '7st March 2019'
const inputZHCN = '7日 三月 2019'
const format = 'Do MMMM YYYY'
expect(dayjs(input, format).valueOf())
.toBe(moment(input, format).valueOf())
expect(dayjs(input2, format).valueOf())
.toBe(moment(input2, format).valueOf())
expect(dayjs(inputFalse, format).valueOf())
.toBe(moment(inputFalse, format).valueOf())
expect(dayjs(inputZHCN, format, 'zh-cn').valueOf())
.toBe(moment(inputZHCN, format, 'zh-cn').valueOf())
})

0 comments on commit bf27fda

Please sign in to comment.