From 97856c603ef5fbbeb1cf8a42387479e56a77dbe8 Mon Sep 17 00:00:00 2001 From: iamkun Date: Thu, 14 May 2020 15:31:38 +0800 Subject: [PATCH] fix: Update CustomParseFormat plugin to support Array formats (#906) --- src/plugin/customParseFormat/index.js | 17 +++++++++++++++-- test/plugin/customParseFormat.test.js | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/plugin/customParseFormat/index.js b/src/plugin/customParseFormat/index.js index 044f62fd..5077a14b 100644 --- a/src/plugin/customParseFormat/index.js +++ b/src/plugin/customParseFormat/index.js @@ -196,11 +196,24 @@ export default (o, C, d) => { locale = pl ? d.Ls[pl] : this.$locale() } this.$d = parseFormattedInput(date, format, utc) - this.init(cfg) + this.init() + if (pl && pl !== true) this.$L = this.locale(pl).$L if (isStrict && date !== this.format(format)) { this.$d = new Date('') } - if (pl && pl !== true) this.$L = this.locale(pl).$L + } else if (format instanceof Array) { + const len = format.length + for (let i = 1; i <= len; i += 1) { + args[1] = format[i - 1] + const result = d.apply(this, args) + if (result.isValid()) { + this.$d = result.$d + this.$L = result.$L + this.init() + break + } + if (i === len) this.$d = new Date('') + } } else { oldParse.call(this, cfg) } diff --git a/test/plugin/customParseFormat.test.js b/test/plugin/customParseFormat.test.js index 0e026031..a326c688 100644 --- a/test/plugin/customParseFormat.test.js +++ b/test/plugin/customParseFormat.test.js @@ -248,3 +248,22 @@ describe('Strict mode', () => { expect(dayjs(input, format, 'zh-cn', true).isValid()).toBe(false) }) }) + +describe('Array format support', () => { + it('second ok', () => { + const input = '2012-05-28' + const format = ['YYYY', 'YYYY-MM-DD'] + expect(dayjs(input, format).isValid()).toBe(true) + expect(dayjs(input, format, true).format('YYYY-MM-DD')).toBe('2012-05-28') + }) + it('all invalid', () => { + const input = '2012-05-28' + const format = ['DD', 'MM-DD'] + expect(dayjs(input, format, true).isValid()).toBe(false) + }) + it('with locale', () => { + const input = '2018 三月 12' + const format = ['YYYY', 'MM', 'YYYY MMMM DD'] + expect(dayjs(input, format, 'zh-cn', true).format('YYYY MMMM DD')).toBe(input) + }) +})