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

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