Explorar el Código

time 工具类

terry hace 2 años
padre
commit
e3d319b2be
Se han modificado 1 ficheros con 58 adiciones y 0 borrados
  1. 58 0
      util/common/time.go

+ 58 - 0
util/common/time.go

@@ -0,0 +1,58 @@
+package common
+
+import (
+	"database/sql/driver"
+	"fmt"
+	"time"
+)
+
+const timeFormat1 = "2006-01-02"
+const timeFormat2 = "2006-01-02 15:04:05"
+const timezone = "Asia/Shanghai"
+
+type Time time.Time
+
+func (t Time) MarshalJSON() ([]byte, error) {
+	b := make([]byte, 0, len(timeFormat2)+2)
+	b = append(b, '"')
+	b = time.Time(t).AppendFormat(b, timeFormat2)
+	b = append(b, '"')
+	return b, nil
+}
+
+func (t *Time) UnmarshalJSON(data []byte) (err error) {
+	timeFormat := timeFormat2
+	if len(data) == 12 {
+		timeFormat = timeFormat1
+	}
+	now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
+	*t = Time(now)
+	return
+}
+
+func (t Time) String() string {
+	return time.Time(t).Format(timeFormat2)
+}
+
+func (t Time) local() time.Time {
+	loc, _ := time.LoadLocation(timezone)
+	return time.Time(t).In(loc)
+}
+
+func (t Time) Value() (driver.Value, error) {
+	var zeroTime time.Time
+	var ti = time.Time(t)
+	if ti.UnixNano() == zeroTime.UnixNano() {
+		return nil, nil
+	}
+	return ti, nil
+}
+
+func (t *Time) Scan(v interface{}) error {
+	value, ok := v.(time.Time)
+	if ok {
+		*t = Time(value)
+		return nil
+	}
+	return fmt.Errorf("can not convert %v to timestamp", v)
+}