github.com/searKing/golang/go@v1.2.117/time/unix_time_day.go (about) 1 package time 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "time" 7 ) 8 9 type UnixTimeDay struct { 10 time.Time 11 } 12 13 func (t UnixTimeDay) unit() time.Duration { 14 return time.Hour * 24 15 } 16 17 func (t UnixTimeDay) String() string { 18 ratio, divide := RatioFrom(time.Second, t.unit()) 19 if divide { 20 return fmt.Sprintf("%d", t.Unix()/int64(ratio)) 21 } 22 return fmt.Sprintf("%d", t.Unix()*int64(ratio)) 23 } 24 25 func (t UnixTimeDay) MarshalJSON() ([]byte, error) { 26 return json.Marshal(t.Unix()) 27 } 28 29 // UnmarshalJSON implements the json.Unmarshaler interface. 30 // The time is expected to be a quoted string in RFC 3339 format. 31 func (t *UnixTimeDay) UnmarshalJSON(data []byte) error { 32 // Ignore null, like in the main JSON package. 33 if string(data) == "null" { 34 return nil 35 } 36 var timestamp int64 37 if err := json.Unmarshal(data, ×tamp); err != nil { 38 return err 39 } 40 t.Time = UnixWithUnit(timestamp, t.unit()) 41 return nil 42 } 43 44 // MarshalText implements the encoding.TextMarshaler interface. 45 // The time is formatted in Unix Seconds, with sub-second precision added if present. 46 func (t UnixTimeDay) MarshalText() ([]byte, error) { 47 return t.MarshalJSON() 48 } 49 50 // UnmarshalText implements the encoding.TextUnmarshaler interface. 51 // The time is expected to be in RFC 3339 format. 52 func (t *UnixTimeDay) UnmarshalText(data []byte) error { 53 return t.UnmarshalJSON(data) 54 }