mirror of
https://github.com/json-iterator/go.git
synced 2025-01-20 18:48:32 +02:00
#67 time as int64 with specified precision
This commit is contained in:
parent
486534c67c
commit
cefb2972fd
@ -7,11 +7,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// keep epoch milliseconds
|
// keep epoch milliseconds
|
||||||
func RegisterTimeAsInt64Codec() {
|
func RegisterTimeAsInt64Codec(precision time.Duration) {
|
||||||
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{})
|
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
|
||||||
}
|
}
|
||||||
|
|
||||||
type timeAsInt64Codec struct {
|
type timeAsInt64Codec struct {
|
||||||
|
precision time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
||||||
@ -20,7 +21,7 @@ func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
|||||||
}
|
}
|
||||||
func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
|
func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
|
||||||
ts := *((*time.Time)(ptr))
|
ts := *((*time.Time)(ptr))
|
||||||
stream.WriteInt64(ts.UnixNano())
|
stream.WriteInt64(ts.UnixNano() / codec.precision.Nanoseconds())
|
||||||
}
|
}
|
||||||
func (codec *timeAsInt64Codec) EncodeInterface(val interface{}, stream *jsoniter.Stream) {
|
func (codec *timeAsInt64Codec) EncodeInterface(val interface{}, stream *jsoniter.Stream) {
|
||||||
jsoniter.WriteToStream(val, stream, codec)
|
jsoniter.WriteToStream(val, stream, codec)
|
||||||
|
@ -9,8 +9,16 @@ 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()
|
RegisterTimeAsInt64Codec(time.Nanosecond)
|
||||||
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
||||||
should.Nil(err)
|
should.Nil(err)
|
||||||
should.Equal("1000001002", string(output))
|
should.Equal("1000001002", string(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Test_time_as_int64_keep_microsecond(t *testing.T) {
|
||||||
|
should := require.New(t)
|
||||||
|
RegisterTimeAsInt64Codec(time.Microsecond)
|
||||||
|
output, err := jsoniter.Marshal(time.Unix(1, 1002))
|
||||||
|
should.Nil(err)
|
||||||
|
should.Equal("1000001", string(output))
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user