Skip to content

Commit

Permalink
fix: update customParseFormat plugin to custom two-digit year parse f…
Browse files Browse the repository at this point in the history
…unction (#1421)
  • Loading branch information
sbrunecker committed Jun 2, 2021
1 parent b728da5 commit bb5df55
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/plugin/customParseFormat/index.js
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions test/plugin/customParseFormat.test.js
Expand Up @@ -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)
})
6 changes: 5 additions & 1 deletion 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<PluginOptions>
export = plugin

0 comments on commit bb5df55

Please sign in to comment.