Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Negative year is considered a valid date #2671

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ Utils.l = parseLocale
Utils.i = isDayjs
Utils.w = wrapper

const hasNegativeDateComponent = (dateStr) => {
// Regular expression to match any part of the date that starts with a hyphen followed by digits
const negativeDatePattern = /(^-|\/-|--|\/-\d{2}|\d{2}\/-\d{2}\/|\d{4}\/-\d{2}|\/-\d{2}\/)/

// Test the date string against the pattern
return negativeDatePattern.test(dateStr)
}

const parseDate = (cfg) => {
const { date, utc } = cfg
if (date === null) return new Date(NaN) // null is invalid
Expand All @@ -77,6 +85,8 @@ const parseDate = (cfg) => {
return new Date(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms)
}

if (hasNegativeDateComponent(date)) return new Date(NaN)
}

return new Date(date) // everything else
Expand Down
3 changes: 3 additions & 0 deletions test/display.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ it('Format no formatStr', () => {
it('Format invalid date', () => {
expect(dayjs('').format()).toBe(new Date('').toString())
expect(dayjs('otherString').format()).toBe(new Date('otherString').toString())
expect(dayjs('-1996/3/2').format()).toBe('Invalid Date')
expect(dayjs('1996/-3/2').format()).toBe('Invalid Date')
expect(dayjs('3/2/-1996').format()).toBe('Invalid Date')
})

it('Format Year YY YYYY', () => {
Expand Down