@@ 210,3 210,29 @@ the Z at the end of rfc3339Timestamp wit
})
}
}
+
+Now let’s implement floating point numbers when there’s no timezone information
+to encode. Because time.Time store its internal time as an integer counting the
+number of nanoseconds since the Epoch, we’ll have to convert it into a floating
+point number in seconds.
+
+ const nanoSecondsInSecond = time.Second / time.Nanosecond
+
+ func (e *Encoder) writeTime(v reflect.Value) error {
+ var t = v.Interface().(time.Time)
+ if t.Location() != time.UTC && t.Location() != nil {
+ if err := e.writeHeader(majorTag, minorTimeString); err != nil {
+ return err
+ }
+ return e.writeUnicodeString(t.Format(time.RFC3339))
+ }
+
+ // write an epoch timestamp to preserve space
+ if err := e.writeHeader(majorTag, minorTimeEpoch); err != nil {
+ return err
+ }
+ var unixTimeNano = t.UnixNano()
+ return e.writeFloat(
+ float64(unixTimeNano) / float64(nanoSecondsInSecond))
+ }
+