Skip to content

Instantly share code, notes, and snippets.

@evangwt
Last active January 19, 2021 06:22
Show Gist options
  • Save evangwt/dfad1e3d787c50eed4ab5a98a05a81b3 to your computer and use it in GitHub Desktop.
Save evangwt/dfad1e3d787c50eed4ab5a98a05a81b3 to your computer and use it in GitHub Desktop.
xorm timestamp
package common
import (
"fmt"
"time"
)
// Timestamp 自定义时间戳类型,支持Mysql的TIMESTAMP,DATETIME,DATE类型
type Timestamp int64
// Time 时间戳转为time.Time
func (t *Timestamp) Time() time.Time {
_, zoneOffset := time.Now().Zone()
return time.Unix(int64(*t)+int64(zoneOffset), 0)
}
func (t *Timestamp) String() string {
return fmt.Sprintf("%d", int64(*t))
}
// FromDB 从db读取
func (t *Timestamp) FromDB(b []byte) error {
d := string(b)
// 字段为DATE类型,值格式为2006-01-02
format := "2006-01-02"
if len(d) > 10 {
format = "2006-01-02 15:04:05"
}
tt, err := time.ParseInLocation(format, d, time.Local)
if err != nil {
return err
}
*t = Timestamp(tt.Unix())
return nil
}
// ToDB 写入db
func (t *Timestamp) ToDB() ([]byte, error) {
tt := time.Unix(int64(*t), 0)
return []byte(tt.Format("2006-01-02 15:04:05")), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment