1
0
mirror of https://github.com/json-iterator/go.git synced 2025-12-23 23:33:38 +02:00

#67 time as int64

This commit is contained in:
Tao Wen
2017-06-20 17:43:47 +08:00
parent ed79b1726e
commit 486534c67c
11 changed files with 77 additions and 34 deletions

View File

@@ -0,0 +1,27 @@
package extra
import (
"github.com/json-iterator/go"
"unsafe"
"time"
)
// keep epoch milliseconds
func RegisterTimeAsInt64Codec() {
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{})
}
type timeAsInt64Codec struct {
}
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
ts := *((*time.Time)(ptr))
return ts.UnixNano() == 0
}
func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
ts := *((*time.Time)(ptr))
stream.WriteInt64(ts.UnixNano())
}
func (codec *timeAsInt64Codec) EncodeInterface(val interface{}, stream *jsoniter.Stream) {
jsoniter.WriteToStream(val, stream, codec)
}

View File

@@ -0,0 +1,16 @@
package extra
import (
"testing"
"time"
"github.com/json-iterator/go/require"
"github.com/json-iterator/go"
)
func Test_time_as_int64(t *testing.T) {
should := require.New(t)
RegisterTimeAsInt64Codec()
output, err := jsoniter.Marshal(time.Unix(1, 1002))
should.Nil(err)
should.Equal("1000001002", string(output))
}