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"
|
|
|
|
)
|
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
// TimeFormat of JSONTime
|
2016-05-23 12:20:58 +00:00
|
|
|
const TimeFormat = "2006-01-02T15:04:05-0700"
|
2016-03-20 16:10:39 +00:00
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
//Time struct of JSONTime
|
2016-03-21 09:12:45 +00:00
|
|
|
type Time struct {
|
|
|
|
time time.Time
|
|
|
|
}
|
2016-03-20 16:10:39 +00:00
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
// Now current 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
|
|
|
}
|
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
//MarshalJSON to bytearray
|
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
|
|
|
|
}
|
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
// UnmarshalJSON from bytearray
|
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
|
|
|
|
}
|
2017-01-20 21:27:44 +00:00
|
|
|
|
|
|
|
// GetTime normal
|
2016-10-08 08:50:41 +00:00
|
|
|
func (t Time) GetTime() time.Time {
|
2016-06-22 07:16:06 +00:00
|
|
|
return t.time
|
|
|
|
}
|
2017-01-20 21:27:44 +00:00
|
|
|
|
|
|
|
// Unix of this time
|
2016-03-21 09:12:45 +00:00
|
|
|
func (t Time) Unix() int64 {
|
|
|
|
return t.time.Unix()
|
|
|
|
}
|
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
// IsZero is time zero?
|
2016-03-21 09:12:45 +00:00
|
|
|
func (t Time) IsZero() bool {
|
|
|
|
return t.time.IsZero()
|
|
|
|
}
|
2016-06-22 07:16:06 +00:00
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
// Add given Duration to this time
|
2016-06-22 07:16:06 +00:00
|
|
|
func (t Time) Add(d time.Duration) Time {
|
|
|
|
return Time{time: t.time.Add(d)}
|
|
|
|
}
|
2017-01-20 21:27:44 +00:00
|
|
|
|
|
|
|
// After is this time after the given?
|
2016-06-22 07:16:06 +00:00
|
|
|
func (t Time) After(u Time) bool {
|
|
|
|
return t.time.After(u.GetTime())
|
|
|
|
}
|
2016-10-08 08:50:41 +00:00
|
|
|
|
2017-01-20 21:27:44 +00:00
|
|
|
// Before is this time before the given?
|
2016-10-08 08:50:41 +00:00
|
|
|
func (t Time) Before(u Time) bool {
|
|
|
|
return t.time.Before(u.GetTime())
|
|
|
|
}
|