sk-matrix-project/backend/golang/matrix-middle-service/pkg/utils/time/time.go

37 lines
802 B
Go
Raw Normal View History

2023-03-14 19:10:45 +08:00
package time
import (
"fmt"
"time"
)
type Time time.Time
const (
timeFormat = "2006-01-02 15:04:05"
)
2023-03-15 11:34:15 +08:00
func (t *Time) String() string {
return fmt.Sprintf("%s", time.Time(*t).Format(timeFormat))
}
2023-03-14 19:10:45 +08:00
// MarshalJSON on Json Time format Time field with %Y-%m-%d %H:%M:%S
func (t *Time) MarshalJSON() ([]byte, error) {
// 重写time转换成json之后的格式
2023-03-15 11:34:15 +08:00
var tmp = fmt.Sprintf("\"%s\"", t.String())
2023-03-14 19:10:45 +08:00
return []byte(tmp), nil
}
func (t *Time) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" {
return nil
}
// Fractional seconds are handled implicitly by Parse.
var err error
2023-03-14 20:19:38 +08:00
loc, _ := time.LoadLocation("Asia/Shanghai")
rawT, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), loc)
2023-03-14 19:10:45 +08:00
*t = Time(rawT)
return err
}