优化 IsValid 方法判断逻辑

This commit is contained in:
gouguoyin 2024-11-29 11:21:54 +08:00
parent cc0bbf8c8e
commit ecda49b9b2
2 changed files with 11 additions and 10 deletions

View File

@ -19,14 +19,10 @@ func (c Carbon) IsZero() bool {
// IsValid reports whether is valid time. // IsValid reports whether is valid time.
// 是否是有效时间 // 是否是有效时间
func (c Carbon) IsValid() bool { func (c Carbon) IsValid() bool {
if c.Error != nil { if c.Error != nil || c.IsZero() {
return false return false
} }
if c.time.IsZero() { if c.Year() >= MinCarbon().Year() && c.Year() <= MaxCarbon().Year() && c.Month() > 0 && c.Day() > 0 {
return false
}
// 大于零值时间
if c.StdTime().Unix() > -62135596800 {
return true return true
} }
return false return false

View File

@ -83,6 +83,11 @@ func TestCarbon_IsZero(t *testing.T) {
carbon: Parse("2020-08-05 00:00:00"), carbon: Parse("2020-08-05 00:00:00"),
want: false, want: false,
}, },
{
name: "case6",
carbon: Parse("0000-01-01 13:14:15"),
want: false,
},
} }
for _, tt := range tests { for _, tt := range tests {
@ -115,8 +120,8 @@ func TestCarbon_IsValid(t *testing.T) {
}, },
{ {
name: "case4", name: "case4",
carbon: Parse("0001-01-01 00:00:00 +0000 UTC"), carbon: Parse("0001-01-01 13:14:15 +0000 UTC"),
want: false, want: true,
}, },
{ {
name: "case5", name: "case5",
@ -155,8 +160,8 @@ func TestCarbon_IsInvalid(t *testing.T) {
}, },
{ {
name: "case4", name: "case4",
carbon: Parse("0001-01-01 00:00:00 +0000 UTC"), carbon: Parse("0001-01-01 13:14:15 +0000 UTC"),
want: true, want: false,
}, },
{ {
name: "case5", name: "case5",