Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package utime
- import (
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "strings"
- "time"
- )
- type UnixTime struct {
- Utime int64
- Valid bool // Valid is true if Time is not NULL
- }
- func NewUnixTime(t time.Time) UnixTime {
- return UnixTime{
- Utime: t.Unix(),
- Valid: true,
- }
- }
- func (nt *UnixTime) Scan(value interface{}) error {
- var err error
- switch x := value.(type) {
- case time.Time:
- nt.Utime = x.Unix()
- fmt.Println("Unixtime.Scan: found time.Time ") // debug
- case []uint8:
- tmpTime, err := time.Parse(time.RFC3339, string(x))
- if err != nil {
- // try parsing with time.RFC3339nano
- tmpTime, err = time.Parse(time.RFC3339Nano, string(x))
- if err != nil {
- nt.Valid = false
- return nil
- }
- }
- nt.Utime = tmpTime.Unix()
- fmt.Println("Unixtime.Scan: tmptime: ", tmpTime) // debug
- case nil:
- fmt.Println("Unixtime.Scan: tmptime is nil") // debug
- nt.Valid = false
- return nil
- default:
- err = fmt.Errorf("null: cannot scan type %T into UnixTime: %v", value, value)
- }
- nt.Valid = err == nil
- return err
- }
- func (nt UnixTime) Value() (driver.Value, error) {
- if !nt.Valid {
- return nil, nil
- }
- return time.Unix(nt.Utime, 0), nil
- }
- func (nt *UnixTime) String() string {
- if !nt.Valid {
- return ""
- }
- return time.Unix(nt.Utime, 0).Format(time.RFC3339)
- }
- func (nt UnixTime) MarshalJSON() ([]byte, error) {
- return json.Marshal(strings.Replace(time.Unix(nt.Utime, 0).Format(time.RFC3339), "+", "Z", -1))
- }
- func (nt *UnixTime) UnmarshalJSON(b []byte) (err error) {
- if b[0] == '"' && b[len(b)-1] == '"' {
- b = b[1 : len(b)-1]
- }
- tmpTime, err := time.Parse(time.RFC3339, string(b))
- if err != nil {
- nt.Valid = false
- return err
- }
- nt.Valid = true
- nt.Utime = tmpTime.Unix()
- return
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement