Skip to content

fix(lunar): reject months, days and leap months that do not exist - #397

Merged
gouguoyin merged 1 commit into
dromara:masterfrom
Kernel-Hunter:fix/lunar-validate-month-day
Nov 13, 2026
Merged

gouguoyin merged 1 commit into
dromara:masterfrom
Kernel-Hunter:fix/lunar-validate-month-day

Conversation

@Kernel-Hunter

Copy link
Copy Markdown
Contributor

lunar.NewLunar and carbon.CreateFromLunar only check that the year is in range, so a date that does not exist is accepted and converted to a real Gregorian day with no error:

carbon.CreateFromLunar(2023, 13, 1, false) // no error
carbon.CreateFromLunar(2023, 1, 31, false) // 2023-02-21, but the first month of 2023 has 29 days
carbon.CreateFromLunar(2024, 1, 1, true)   // 2024-03-10, but 2024 has no leap month
carbon.CreateFromLunar(2023, 5, 1, true)   // 2023-07-18, but the leap month of 2023 is the second one

The offset math in ToGregorian just adds the day to the start of the month, so an impossible date rolls into the next month instead of failing. Month 0 and day 0 go backwards the same way.

IsValid now also checks that the month is 1 to 12, that the day fits the month (using getDaysInMonth / getDaysInLeapMonth), and that a leap month is the year's actual leap month. While there I fixed the error text in NewLunar, which said "invalid persian date" and checked IsValid twice.

To make sure nothing valid is rejected, I ran every day from 1900-01-31 to 2101-01-28 through FromStdTime, rebuilt it with NewLunar and converted it back with ToGregorian. All 73,384 days passed both checks.

The new cases in TestLunar_IsValid and TestCreateFromLunar fail on master and pass with this change. go test ./... and go vet ./... pass.

@gouguoyin
gouguoyin merged commit 811fe7e into dromara:master Nov 13, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants