1 Star 0 Fork 0

igo/pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
time.go 1.57 KB
一键复制 编辑 原始数据 按行查看 历史
layte.xiao 提交于 2022-10-15 11:20 . init
package xtime
import (
"database/sql/driver"
"fmt"
"time"
)
const (
DateFormatTimestamp = "2006-01-02 15:04:05.000000"
DateFormatLine = "2006/01/02 15:04:05"
DateFormatLineV2 = "2006-01-02 15:04:05"
DateFormatLineV3 = "2006-01-02"
DateYmdNoLine = "20060102"
DateymdNoLine = "060102"
DateYmdNoLineV2 = "20060102150405"
DateYmdNoLineV3 = "200601"
)
type Time time.Time
// Scan 实现 sql.Scanner 接口,处理从数据库里拿出的值
func (t *Time) Scan(value interface{}) error {
switch vt := value.(type) {
case string:
tTime, err := time.ParseInLocation(DateFormatLineV2, vt, time.Local)
if err != nil {
return err
}
*t = Time(tTime)
case time.Time:
*t = Time(vt)
return nil
}
return fmt.Errorf("scan value type err")
}
// Value 实现 driver.Valuer 接口,处理将要写入数据库的值
func (t Time) Value() (driver.Value, error) {
if t.Time().IsZero() {
return nil, nil
}
return time.Time(t), nil
}
// Time get time.
func (t Time) Time() time.Time {
return time.Time(t)
}
func (t *Time) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+DateFormatLineV2+`"`, string(data), time.Local)
*t = Time(now)
return
}
func (t Time) MarshalJSON() ([]byte, error) {
if t.Time().IsZero() {
return []byte{'"', '"'}, nil
}
b := make([]byte, 0, len(DateFormatLineV2)+2)
b = append(b, '"')
b = time.Time(t).AppendFormat(b, DateFormatLineV2)
b = append(b, '"')
return b, nil
}
func (t Time) String() string {
if t.Time().IsZero() {
return ""
}
return time.Time(t).Format(DateFormatLineV2)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/igolang/pkg.git
git@gitee.com:igolang/pkg.git
igolang
pkg
pkg
v1.20.6

搜索帮助