amuz.es/src/go/misc@v1.0.1/types/time.go (about)

     1  package types
     2  
     3  import (
     4  	"amuz.es/src/go/misc"
     5  	jsoniter "github.com/json-iterator/go"
     6  	"time"
     7  
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  type JSONTime time.Time
    12  
    13  func (dttm JSONTime) MarshalJSON() ([]byte, error) {
    14  	stream := misc.JSONCodec.BorrowStream(nil)
    15  	defer misc.JSONCodec.ReturnStream(stream)
    16  	stream.WriteInt64(time.Time(dttm).UTC().Unix())
    17  	return append([]byte(nil), stream.Buffer()...), stream.Error
    18  }
    19  
    20  func (dttm *JSONTime) UnmarshalJSON(b []byte) error {
    21  	iterator := misc.JSONCodec.BorrowIterator(b)
    22  	defer misc.JSONCodec.ReturnIterator(iterator)
    23  	valueType := iterator.WhatIsNext()
    24  	switch valueType {
    25  	case jsoniter.NumberValue:
    26  		*dttm = JSONTime(time.Unix(iterator.ReadInt64(), 0))
    27  		return nil
    28  	default:
    29  		return errors.Errorf("%d is wrong type", valueType)
    30  	}
    31  }