github.com/newrelic/newrelic-client-go@v1.1.0/internal/serialization/epoch_time.go (about) 1 package serialization 2 3 import ( 4 "fmt" 5 "strconv" 6 "time" 7 ) 8 9 // EpochTime is a type used for unmarshaling timestamps represented in epoch time. 10 // Its underlying type is time.Time. 11 type EpochTime time.Time 12 13 // MarshalJSON is responsible for marshaling the EpochTime type. 14 func (e EpochTime) MarshalJSON() ([]byte, error) { 15 ret := strconv.FormatInt(time.Time(e).UTC().Unix(), 10) 16 milli := int64(time.Time(e).Nanosecond()) / int64(time.Millisecond) 17 18 // Include milliseconds if there are some 19 if milli > 0 { 20 ret += fmt.Sprintf("%03d", milli) 21 } 22 23 return []byte(ret), nil 24 } 25 26 // UnmarshalJSON is responsible for unmarshaling the EpochTime type. 27 func (e *EpochTime) UnmarshalJSON(s []byte) error { 28 var ( 29 err error 30 sec int64 31 milli int64 32 nano int64 33 ) 34 35 // detect type of timestamp based on length 36 switch l := len(s); { 37 case l <= 10: // seconds 38 sec, err = strconv.ParseInt(string(s), 10, 64) 39 case l > 10 && l <= 16: // milliseconds 40 milli, err = strconv.ParseInt(string(s[0:13]), 10, 64) 41 if err != nil { 42 return err 43 } 44 nano = milli * int64(time.Millisecond) 45 case l > 16: // nanoseconds 46 sec, err = strconv.ParseInt(string(s[0:10]), 10, 64) 47 if err != nil { 48 return err 49 } 50 nano, err = strconv.ParseInt(string(s[10:16]), 10, 64) 51 default: 52 return fmt.Errorf("unable to parse EpochTime: '%s'", s) 53 } 54 55 if err != nil { 56 return err 57 } 58 59 // Convert and self store 60 *(*time.Time)(e) = time.Unix(sec, nano).UTC() 61 62 return nil 63 } 64 65 // Equal provides a comparator for the EpochTime type. 66 func (e EpochTime) Equal(u EpochTime) bool { 67 return time.Time(e).Equal(time.Time(u)) 68 } 69 70 // String returns the time formatted using the format string 71 func (e EpochTime) String() string { 72 return time.Time(e).String() 73 } 74 75 // Unix returns the time formatted as seconds since Jan 1st, 1970 76 func (e EpochTime) Unix() int64 { 77 return time.Time(e).Unix() 78 }