mirror of
https://github.com/json-iterator/go.git
synced 2025-05-16 21:45:43 +02:00
#67 time as int64 with decoder
This commit is contained in:
parent
cefb2972fd
commit
83fa27ff9a
@ -9,11 +9,16 @@ import (
|
|||||||
// keep epoch milliseconds
|
// keep epoch milliseconds
|
||||||
func RegisterTimeAsInt64Codec(precision time.Duration) {
|
func RegisterTimeAsInt64Codec(precision time.Duration) {
|
||||||
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
|
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
|
||||||
|
jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
|
||||||
}
|
}
|
||||||
|
|
||||||
type timeAsInt64Codec struct {
|
type timeAsInt64Codec struct {
|
||||||
precision time.Duration
|
precision time.Duration
|
||||||
}
|
}
|
||||||
|
func (codec *timeAsInt64Codec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||||
|
nanoseconds := iter.ReadInt64() * codec.precision.Nanoseconds()
|
||||||
|
*((*time.Time)(ptr)) = time.Unix(0, nanoseconds)
|
||||||
|
}
|
||||||
|
|
||||||
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
ts := *((*time.Time)(ptr))
|
ts := *((*time.Time)(ptr))
|
||||||
|
@ -10,9 +10,12 @@ import (
|
|||||||
func Test_time_as_int64(t *testing.T) {
|
func Test_time_as_int64(t *testing.T) {
|
||||||
should := require.New(t)
|
should := require.New(t)
|
||||||
RegisterTimeAsInt64Codec(time.Nanosecond)
|
RegisterTimeAsInt64Codec(time.Nanosecond)
|
||||||
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
output, err := jsoniter.Marshal(time.Unix(1497952257, 1002))
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal("1000001002", string(output))
|
should.Equal("1497952257000001002", string(output))
|
||||||
|
var val time.Time
|
||||||
|
should.Nil(jsoniter.Unmarshal(output, &val))
|
||||||
|
should.Equal(int64(1497952257000001002), val.UnixNano())
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_time_as_int64_keep_microsecond(t *testing.T) {
|
func Test_time_as_int64_keep_microsecond(t *testing.T) {
|
||||||
@ -21,4 +24,7 @@ func Test_time_as_int64_keep_microsecond(t *testing.T) {
|
|||||||
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal("1000001", string(output))
|
should.Equal("1000001", string(output))
|
||||||
|
var val time.Time
|
||||||
|
should.Nil(jsoniter.Unmarshal(output, &val))
|
||||||
|
should.Equal(int64(1000001000), val.UnixNano())
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user