github.com/searKing/golang/go@v1.2.117/time/unix_time_nano.go (about)

     1  package time
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  type UnixTimeNanosecond struct {
    10  	time.Time
    11  }
    12  
    13  func (t UnixTimeNanosecond) unit() time.Duration {
    14  	return time.Nanosecond
    15  }
    16  
    17  func (t UnixTimeNanosecond) String() string {
    18  	return fmt.Sprintf("%d", t.UnixNano())
    19  }
    20  
    21  func (t UnixTimeNanosecond) MarshalJSON() ([]byte, error) {
    22  	return json.Marshal(t.UnixNano())
    23  }
    24  
    25  // UnmarshalJSON implements the json.Unmarshaler interface.
    26  // The time is expected to be a quoted string in RFC 3339 format.
    27  func (t *UnixTimeNanosecond) UnmarshalJSON(data []byte) error {
    28  	// Ignore null, like in the main JSON package.
    29  	if string(data) == "null" {
    30  		return nil
    31  	}
    32  	var timestamp int64
    33  	if err := json.Unmarshal(data, &timestamp); err != nil {
    34  		return err
    35  	}
    36  	t.Time = UnixWithUnit(timestamp, t.unit())
    37  	return nil
    38  }
    39  
    40  // MarshalText implements the encoding.TextMarshaler interface.
    41  // The time is formatted in Unix Seconds, with sub-second precision added if present.
    42  func (t UnixTimeNanosecond) MarshalText() ([]byte, error) {
    43  	return t.MarshalJSON()
    44  }
    45  
    46  // UnmarshalText implements the encoding.TextUnmarshaler interface.
    47  // The time is expected to be in RFC 3339 format.
    48  func (t *UnixTimeNanosecond) UnmarshalText(data []byte) error {
    49  	return t.UnmarshalJSON(data)
    50  }