enhance(types):增加不同日期时间格式的解析。
This commit is contained in:
parent
50418f2e30
commit
686890b5d8
|
@ -10,6 +10,10 @@ import (
|
||||||
"go.uber.org/zap"
|
"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 {
|
type Date struct {
|
||||||
time.Time
|
time.Time
|
||||||
}
|
}
|
||||||
|
@ -42,13 +46,15 @@ func ParseDate(t string) (Date, error) {
|
||||||
if len(t) == 0 {
|
if len(t) == 0 {
|
||||||
return NewEmptyDate(), fmt.Errorf("不能解析空白的日期时间。")
|
return NewEmptyDate(), fmt.Errorf("不能解析空白的日期时间。")
|
||||||
}
|
}
|
||||||
d, err := time.ParseInLocation("2006-01-02", t, loc)
|
for _, layout := range dateLayouts {
|
||||||
if err != nil {
|
d, err := time.ParseInLocation(layout, t, loc)
|
||||||
return NewEmptyDate(), fmt.Errorf("无法解析给定的日期, %w", err)
|
if err == nil {
|
||||||
}
|
|
||||||
return Date{
|
return Date{
|
||||||
Time: d,
|
Time: d,
|
||||||
}, nil
|
}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NewEmptyDate(), fmt.Errorf("无法解析给定的日期,格式不正确。")
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseDateWithDefault(t string, defaultDate Date) Date {
|
func ParseDateWithDefault(t string, defaultDate Date) Date {
|
||||||
|
|
|
@ -10,7 +10,12 @@ import (
|
||||||
"go.uber.org/zap"
|
"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 {
|
type DateTime struct {
|
||||||
time.Time
|
time.Time
|
||||||
|
@ -43,13 +48,15 @@ func ParseDateTime(t string) (DateTime, error) {
|
||||||
if len(t) == 0 {
|
if len(t) == 0 {
|
||||||
return NewEmptyDateTime(), fmt.Errorf("不能解析空白的日期时间。")
|
return NewEmptyDateTime(), fmt.Errorf("不能解析空白的日期时间。")
|
||||||
}
|
}
|
||||||
d, err := time.ParseInLocation("2006-01-02 13:04:05", t, loc)
|
for _, layout := range datetimeLayouts {
|
||||||
if err != nil {
|
d, err := time.ParseInLocation(layout, t, loc)
|
||||||
return NewEmptyDateTime(), fmt.Errorf("无法解析给定的日期, %w", err)
|
if err == nil {
|
||||||
}
|
|
||||||
return DateTime{
|
return DateTime{
|
||||||
Time: d,
|
Time: d,
|
||||||
}, nil
|
}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NewEmptyDateTime(), fmt.Errorf("无法解析给定的日期时间,格式不正确。")
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ driver.Valuer = (*DateTime)(nil)
|
var _ driver.Valuer = (*DateTime)(nil)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user