1 Star 0 Fork 0

xlizy/common-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
xtime.go 1.29 KB
一键复制 编辑 原始数据 按行查看 历史
xlizy 提交于 2024-04-09 16:16 . init
package xtime
import (
"database/sql/driver"
"fmt"
"gitee.com/xlizy/common-go/base/const"
"strings"
"time"
)
type Time struct {
time.Time
}
func (t Time) MarshalJSON() ([]byte, error) {
if t.Time.IsZero() {
return []byte("\"\""), nil
}
return []byte("\"" + t.Time.Format(constant.DataFormat) + "\""), nil
}
func (t *Time) UnmarshalJSON(value []byte) (err error) {
var date time.Time
layouts := []string{"2006-01-02T15:04:05-0700", "2006-01-02 15:04:05-0700", "2006-01-02 15:04:05", "2006-01-02"}
for _, layout := range layouts {
date, err = time.Parse(layout, strings.Replace(string(value), "\"", "", -1))
if err == nil {
t.Time = date
break
}
}
return
}
func (t Time) Value() (driver.Value, error) {
if t.Time.IsZero() {
return nil, nil
} else {
return t.Time.Format("2006-01-02 15:04:05"), nil
}
}
func (t *Time) Scan(value interface{}) (err error) {
if value == nil {
t.Time = time.Time{}
return nil
}
tm, ok := value.(time.Time)
if !ok {
var date time.Time
layouts := []string{"2006-01-02T15:04:05-0700", "2006-01-02 15:04:05-0700", "2006-01-02 15:04:05", "2006-01-02"}
for _, layout := range layouts {
date, err = time.Parse(layout, fmt.Sprintf("%v", value))
if err == nil {
t.Time = date
break
}
}
return
}
t.Time = tm
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/xlizy/common-go.git
git@gitee.com:xlizy/common-go.git
xlizy
common-go
common-go
v0.0.27

搜索帮助

0d507c66 1850385 C8b1a773 1850385