Fix jsontime and extend tests
This commit is contained in:
parent
150d9b3297
commit
603bd57b45
@ -1,25 +1,39 @@
|
||||
package jsontime
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
const TimeFormat = "2006-01-02T15:04:05"
|
||||
|
||||
type Time time.Time
|
||||
type Time struct {
|
||||
time time.Time
|
||||
}
|
||||
|
||||
func Now() Time {
|
||||
return Time(time.Now())
|
||||
return Time{time.Now()}
|
||||
}
|
||||
|
||||
func (t Time) MarshalJSON() ([]byte, error) {
|
||||
stamp := `"` + time.Time(t).Format(TimeFormat) + `"`
|
||||
stamp := `"` + t.time.Format(TimeFormat) + `"`
|
||||
return []byte(stamp), nil
|
||||
}
|
||||
|
||||
func (t Time) UnmarshalJSON(data []byte) (err error) {
|
||||
if nativeTime, err := time.Parse(TimeFormat, string(data)); err == nil {
|
||||
t = Time(nativeTime)
|
||||
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
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (t Time) Unix() int64 {
|
||||
return t.time.Unix()
|
||||
}
|
||||
|
||||
func (t Time) IsZero() bool {
|
||||
return t.time.IsZero()
|
||||
}
|
||||
|
@ -1,20 +1,28 @@
|
||||
package jsontime
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNow(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
t1 := time.Now()
|
||||
t2 := Now()
|
||||
|
||||
assert.InDelta(t1.Unix(), t2.Unix(), 1)
|
||||
}
|
||||
|
||||
func TestMarshalTime(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
nativeTime, err := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00")
|
||||
assert.Nil(err)
|
||||
|
||||
json, err := Time(nativeTime).MarshalJSON()
|
||||
json, err := Time{nativeTime}.MarshalJSON()
|
||||
assert.Nil(err)
|
||||
|
||||
assert.Equal(`"2012-11-01T22:08:41"`, string(json))
|
||||
@ -24,6 +32,7 @@ func TestUnmarshalTime(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
jsonTime := Time{}
|
||||
|
||||
err := json.Unmarshal([]byte(`"2012-11-01T22:08:41"`), &jsonTime)
|
||||
err := jsonTime.UnmarshalJSON([]byte(`"2012-11-01T22:08:41"`))
|
||||
assert.Nil(err)
|
||||
assert.False(jsonTime.IsZero())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user