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

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