-
Notifications
You must be signed in to change notification settings - Fork 18.3k
Description
Initial tl;dr: Go could make timestamp handling much easier by providing the following functions in its time library:
func (t Time) UnixMicro() int64 { ... }
func (t Time) UnixMilli() int64 { ... }
func FromUnixMicro(us int64) Time { ... }
func FromUnixMilli(ms int64) Time { ... }
Golang has time.Time as the idiomatic way of representing a time. However, not every API we encounter has this, and lots of them return Unix-style timestamps as int64 (sometimes uint64) in units of ms, us, or ns. For example, this will always occur when using API's that operate on protocol buffers, which use integers for timestamps instead of a native time type.
If we happen to have nanosecond timestamps, go is pretty nice. However, if we're using microseconds, then it gets fairly annoying to use time.Time, as you'll have to do error-prone type conversions everywhere, or rely on a timeutil library you write yourself for something which feels like it should be built in.
This is the type of stuff we have to do right now when dealing with niceapi that uses time.Time and otherapi that uses microseconds:
ts := otherapi.GetTimestamp()
t := time.Unix(0, ts * 1000) // one unit conversion, potential cause for bugs
niceapi.Use(t)
// elsewhere
t := niceApi.WhatTime()
ts := t.UnixNano() / 1000 // second unit conversion, potential cause for bugs
otherApi.Use(ts)
But why not
t := time.FromUnixMicro(otherapi.GetTimestamp()) // seems way less error prone to me
niceapi.Use(t)
// elsewhere
ts := niceApi.WhatTime().UnixMicro() // so easy!
otherApi.Use(ts)