From bb5df55cd3975dc7638b8f4e762afa470b6620f7 Mon Sep 17 00:00:00 2001 From: Stefan Brunecker <33121464+sbrunecker@users.noreply.github.com> Date: Wed, 2 Jun 2021 09:32:43 +0200 Subject: [PATCH] fix: update customParseFormat plugin to custom two-digit year parse function (#1421) --- src/plugin/customParseFormat/index.js | 11 +++++++++-- test/plugin/customParseFormat.test.js | 13 +++++++++++++ types/plugin/customParseFormat.d.ts | 6 +++++- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/plugin/customParseFormat/index.js b/src/plugin/customParseFormat/index.js index d9251dbde..536a6654c 100644 --- a/src/plugin/customParseFormat/index.js +++ b/src/plugin/customParseFormat/index.js @@ -13,6 +13,11 @@ const matchWord = /\d*[^\s\d-_:/()]+/ // Word let locale = {} +let parseTwoDigitYear = function (input) { + input = +input + return input + (input > 68 ? 1900 : 2000) +} + function offsetFromString(string) { if (!string) return 0 if (string === 'Z') return 0 @@ -111,8 +116,7 @@ const expressions = { }], Y: [matchSigned, addInput('year')], YY: [match2, function (input) { - input = +input - this.year = input + (input > 68 ? 1900 : 2000) + this.year = parseTwoDigitYear(input) }], YYYY: [match4, addInput('year')], Z: zoneExpressions, @@ -201,6 +205,9 @@ const parseFormattedInput = (input, format, utc) => { export default (o, C, d) => { d.p.customParseFormat = true + if (o && o.parseTwoDigitYear) { + ({ parseTwoDigitYear } = o) + } const proto = C.prototype const oldParse = proto.parse proto.parse = function (cfg) { diff --git a/test/plugin/customParseFormat.test.js b/test/plugin/customParseFormat.test.js index b6e06a7d9..65a702997 100644 --- a/test/plugin/customParseFormat.test.js +++ b/test/plugin/customParseFormat.test.js @@ -355,3 +355,16 @@ it('parse a string for MMM month format with underscore delimiter', () => { expect(dayjs(input2, format2).valueOf()).toBe(moment(input2, format2).valueOf()) }) +it('custom two-digit year parse function', () => { + delete customParseFormat.$i // this allow plugin to be installed again + dayjs.extend(customParseFormat, { + parseTwoDigitYear: yearString => (+yearString) + 1800 + }) + const format = 'YY-MM-DD' + const input = '00-05-02' + expect(dayjs(input, format).year()).toBe(1800) + const input2 = '50-05-02' + expect(dayjs(input2, format).year()).toBe(1850) + const input3 = '99-05-02' + expect(dayjs(input3, format).year()).toBe(1899) +}) diff --git a/types/plugin/customParseFormat.d.ts b/types/plugin/customParseFormat.d.ts index 30ec75e5d..1b41c0d8d 100644 --- a/types/plugin/customParseFormat.d.ts +++ b/types/plugin/customParseFormat.d.ts @@ -1,4 +1,8 @@ import { PluginFunc } from 'dayjs' -declare const plugin: PluginFunc +declare interface PluginOptions { + parseTwoDigitYear?: (yearString: string) => number +} + +declare const plugin: PluginFunc export = plugin