iamkun / iamkun/dayjs

Invalid month number with customParseFormat leads to the next year date

Open
#2,249 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
48.7k
Forks
2.5k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**

First of all thank your great product.

Sometimes we use formats like that `D MMMM` and want to get proper date representation but we found a bug when have been working with dayjs's plugin `customParseFormat` with `locale/ru` locale.

We found it when use the last month in the special format (`2 декабря`) -> `декабря`.

```
console.log('Valid date', parseFormattedInput('2 января', 'D MMMM', true)); // 2023-01-02T00:00:00.000Z
console.log('Valid date', parseFormattedInput('2 ноября', 'D MMMM', true)); // 2023-11-02T00:00:00.000Z
console.log('Invalid date', parseFormattedInput('2 декабря', 'D MMMM', true)); // 2024-12-02T00:00:00.000Z - it takes next year since these lines of code
```

Calculation here is a bit broken:

```
MMM: // almost safe for this case
MMMM: [matchWord, function (input) {
const months = getLocalePart('months')
const matchIndex = months.indexOf(input) + 1
if (matchIndex < 1) {
throw new Error()
}
this.month = (matchIndex % 12) || matchIndex
}],
```

Pay attention at this line `this.month = (matchIndex % 12) || matchIndex`, when we have `matchIndex = 24, because index of a month is 23 + 1 to get month number` then it takes this number because `24%12=0` so right branch is going ahead. But `24` means in the scope of `Date` "take next year and add `12` months to it" what is wrong.

**Expected behaviuor**
```
console.log('Valid date', parseFormattedInput('2 января', 'D MMMM', true)); // 2023-01-02T00:00:00.000Z
console.log('Valid date', parseFormattedInput('2 ноября', 'D MMMM', true)); // 2023-11-02T00:00:00.000Z
console.log('Valid date', parseFormattedInput('2 декабря', 'D MMMM', true)); // 2023-12-02T00:00:00.000Z
```

**Information**
- Day.js Version [v1.8.29]
- OS: [MacOS]
- Browser [chrome 110.0.5481.177]
- Time zone: [GMT+3]

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.