2016-03-20 16:10:39 +00:00
|
|
|
package jsontime
|
|
|
|
|
|
|
|
import (
|
2016-03-21 09:12:45 +00:00
|
|
|
"errors"
|
2016-03-20 16:10:39 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2016-05-23 12:20:58 +00:00
|
|
|
const TimeFormat = "2006-01-02T15:04:05-0700"
|
2016-03-20 16:10:39 +00:00
|
|
|
|
2016-03-21 09:12:45 +00:00
|
|
|
type Time struct {
|
|
|
|
time time.Time
|
|
|
|
}
|
2016-03-20 16:10:39 +00:00
|
|
|
|
|
|
|
func Now() Time {
|
2016-03-21 09:12:45 +00:00
|
|
|
return Time{time.Now()}
|
2016-03-20 16:10:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t Time) MarshalJSON() ([]byte, error) {
|
2016-03-21 09:12:45 +00:00
|
|
|
stamp := `"` + t.time.Format(TimeFormat) + `"`
|
2016-03-20 16:10:39 +00:00
|
|
|
return []byte(stamp), nil
|
|
|
|
}
|
|
|
|
|
2016-03-21 09:12:45 +00:00
|
|
|
func (t *Time) UnmarshalJSON(data []byte) (err error) {
|
|
|
|
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
|
|
|
|
return errors.New("invalid jsontime")
|
|
|
|
}
|
|
|
|
if nativeTime, err := time.Parse(TimeFormat, string(data[1:len(data)-1])); err == nil {
|
|
|
|
t.time = nativeTime
|
2016-03-20 16:10:39 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2016-03-21 09:12:45 +00:00
|
|
|
|
|
|
|
func (t Time) Unix() int64 {
|
|
|
|
return t.time.Unix()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t Time) IsZero() bool {
|
|
|
|
return t.time.IsZero()
|
|
|
|
}
|