From 686890b5d8a8612defdc048651b38deb3cc9187e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Sat, 10 Jun 2023 11:26:10 +0800 Subject: [PATCH] =?UTF-8?q?enhance(types):=E5=A2=9E=E5=8A=A0=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E6=97=A5=E6=9C=9F=E6=97=B6=E9=97=B4=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E6=9E=90=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- types/date.go | 18 ++++++++++++------ types/datetime.go | 21 ++++++++++++++------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/types/date.go b/types/date.go index 6713219..7e08394 100644 --- a/types/date.go +++ b/types/date.go @@ -10,6 +10,10 @@ import ( "go.uber.org/zap" ) +var dateLayouts = []string{ + "2006-01-02", "2006-1-2", "2006/01/02", "6-1-2", "6-01-02", "01/02/06", "1/2/6", "2006年01月02日", "06年1月2日", +} + type Date struct { time.Time } @@ -42,13 +46,15 @@ func ParseDate(t string) (Date, error) { if len(t) == 0 { return NewEmptyDate(), fmt.Errorf("不能解析空白的日期时间。") } - d, err := time.ParseInLocation("2006-01-02", t, loc) - if err != nil { - return NewEmptyDate(), fmt.Errorf("无法解析给定的日期, %w", err) + for _, layout := range dateLayouts { + d, err := time.ParseInLocation(layout, t, loc) + if err == nil { + return Date{ + Time: d, + }, nil + } } - return Date{ - Time: d, - }, nil + return NewEmptyDate(), fmt.Errorf("无法解析给定的日期,格式不正确。") } func ParseDateWithDefault(t string, defaultDate Date) Date { diff --git a/types/datetime.go b/types/datetime.go index ea5a41e..6d70a42 100644 --- a/types/datetime.go +++ b/types/datetime.go @@ -10,7 +10,12 @@ import ( "go.uber.org/zap" ) -var loc *time.Location = time.FixedZone("+0800", 8*60*60) +var ( + loc *time.Location = time.FixedZone("+0800", 8*60*60) + datetimeLayouts = []string{ + "2006-01-02 15:04:05", "2006-1-2 15:04:05", "2006/01/02 15:04:05", "6-1-2 15:04:05", "6-01-02 15:04:05", "01/02/06 15:04:05", "1/2/6 15:04:05", "2006年01月02日 15:04:05", "06年1月2日 15:04:05", + } +) type DateTime struct { time.Time @@ -43,13 +48,15 @@ func ParseDateTime(t string) (DateTime, error) { if len(t) == 0 { return NewEmptyDateTime(), fmt.Errorf("不能解析空白的日期时间。") } - d, err := time.ParseInLocation("2006-01-02 13:04:05", t, loc) - if err != nil { - return NewEmptyDateTime(), fmt.Errorf("无法解析给定的日期, %w", err) + for _, layout := range datetimeLayouts { + d, err := time.ParseInLocation(layout, t, loc) + if err == nil { + return DateTime{ + Time: d, + }, nil + } } - return DateTime{ - Time: d, - }, nil + return NewEmptyDateTime(), fmt.Errorf("无法解析给定的日期时间,格式不正确。") } var _ driver.Valuer = (*DateTime)(nil)