yanic/jsontime/jsontime.go

67 lines
1.3 KiB
Go
Raw Normal View History

2016-03-20 17:10:39 +01:00
package jsontime
import (
2016-03-21 10:12:45 +01:00
"errors"
2016-03-20 17:10:39 +01:00
"time"
)
// TimeFormat of JSONTime
2016-05-23 14:20:58 +02:00
const TimeFormat = "2006-01-02T15:04:05-0700"
2016-03-20 17:10:39 +01:00
//Time struct of JSONTime
2016-03-21 10:12:45 +01:00
type Time struct {
time time.Time
}
2016-03-20 17:10:39 +01:00
// Now current Time
2016-03-20 17:10:39 +01:00
func Now() Time {
2016-03-21 10:12:45 +01:00
return Time{time.Now()}
2016-03-20 17:10:39 +01:00
}
//MarshalJSON to bytearray
2016-03-20 17:10:39 +01:00
func (t Time) MarshalJSON() ([]byte, error) {
2016-03-21 10:12:45 +01:00
stamp := `"` + t.time.Format(TimeFormat) + `"`
2016-03-20 17:10:39 +01:00
return []byte(stamp), nil
}
// UnmarshalJSON from bytearray
2016-03-21 10:12:45 +01: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 17:10:39 +01:00
}
return
}
// GetTime normal
func (t Time) GetTime() time.Time {
return t.time
}
// Unix of this time
2016-03-21 10:12:45 +01:00
func (t Time) Unix() int64 {
return t.time.Unix()
}
// IsZero is time zero?
2016-03-21 10:12:45 +01:00
func (t Time) IsZero() bool {
return t.time.IsZero()
}
// Add given Duration to this time
func (t Time) Add(d time.Duration) Time {
return Time{time: t.time.Add(d)}
}
// After is this time after the given?
func (t Time) After(u Time) bool {
return t.time.After(u.GetTime())
}
// Before is this time before the given?
func (t Time) Before(u Time) bool {
return t.time.Before(u.GetTime())
}