123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- package models
- import (
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "strconv"
- "strings"
- "time"
- "gogs.baozhida.cn/Cold_Logistic_libs/pkg/contrib/errors"
- )
- type BaseEntity interface {
- TableName() string
- }
- func NewMyTime(t time.Time) MyTime {
- return MyTime{Time: t}
- }
- type MyTime struct {
- time.Time
- }
- // UnmarshalJSON ..
- func (d *MyTime) UnmarshalJSON(b []byte) (err error) {
- s := strings.Trim(string(b), "\"")
- if s == "null" || s == "0" {
- d.Time, err = time.Parse("2006-01-02 15:04:05.000", "0001-01-01 00:00:00.000")
- return err
- }
- if len(s) > 0 && len(s) <= 13 {
- millSec, err := strconv.ParseInt(s, 10, 64)
- if err != nil {
- return err
- }
- d.Time = time.UnixMilli(millSec)
- } else {
- return errors.New("invalid timestamp")
- }
- return nil
- }
- // MarshalJSON ..
- func (d MyTime) MarshalJSON() ([]byte, error) {
- if d.Time.Year() < 1800 {
- return json.Marshal(0)
- }
- return json.Marshal(d.Time.UnixMilli())
- }
- // Scan 从数据库读取进行绑定时用到
- func (d *MyTime) Scan(b interface{}) (err error) {
- switch x := b.(type) {
- case time.Time:
- d.Time = x
- case []byte:
- t, err := time.Parse("2006-01-02 15:04:05.000", string(b.([]byte)))
- if err != nil {
- return errors.Wrap(err, fmt.Sprintf("从数据库绑定DateTime时出错: %s", err))
- }
- d.Time = t
- default:
- d.Time = time.Time{}
- }
- return nil
- }
- // Value 写入数据库时用到
- func (d MyTime) Value() (driver.Value, error) {
- if d.Time.IsZero() {
- return `0001-01-01 00:00:00`, nil
- }
- v := d.Time.Format("2006-01-02 15:04:05.000")
- return v, nil
- }
- func (d *MyTime) GetMillSec() int64 {
- if d.Time.IsZero() {
- return 0
- }
- return d.Time.UnixMilli()
- }
- func (d MyTime) GetYearFirstDay() MyTime {
- if d.Time.IsZero() {
- d.Time = time.Now()
- }
- startOfYear := time.Date(d.Time.Year(), time.January, 1, 0, 0, 0, 0, time.Local)
- return MyTime{Time: startOfYear}
- }
- // 是否删除
- const (
- DeleteYes = 1
- DeleteNo = 2
- )
- type TimeStatType string
- const (
- TimeStatYear TimeStatType = "year" // 年
- TimeStatMonth TimeStatType = "month" // 月
- TimeStatDay TimeStatType = "day" // 日
- )
- func (e TimeStatType) Format(column, alias string) string {
- str := ""
- switch e {
- case TimeStatYear:
- str = fmt.Sprintf("DATE_FORMAT(%s,'%Y') ", column)
- case TimeStatMonth:
- str = fmt.Sprintf("DATE_FORMAT(%s,'%Y-%m') ", column)
- case TimeStatDay:
- str = fmt.Sprintf("DATE(%s) ", column)
- default:
- str = fmt.Sprintf("DATE(%s) ", column)
- }
- if alias != "" {
- str += fmt.Sprintf("AS %s ", alias)
- }
- return str
- }
|