This library offers a timestamp struct that is SQL-compatible and marshals/unmarshals as epoch seconds. It also offers a nullable version.
Traditionally, time.Time
gets serialized and deserialized using RFC3339 rather than epoch seconds.
There is a workaround
you can use to create your own wrapper over time.Time
.
However, there are two additional requirements many apps need:
- timestamps need SQL support
- timestamps need to be nullable sometimes
For SQL support, we implement the Value interface. For nullability, we borrow heavily from guregu/null.
package main
import (
"time"
"github.com/hanakoa/epoch-time"
)
type Invitation struct {
CreatedTime epoch.Time `json:"created_time"`
ApprovedTime epoch.NullTime `json:"approved_time"`
}
func main() {
var b []byte
var err error
i := Invitation{
CreatedTime: epoch.Time(time.Date(1993, 04, 17, 23, 0, 0, 0, time.UTC)),
ApprovedTime: epoch.NullTimeFromPtr(nil),
}
b, err = json.Marshal(i)
// prints `{"created_time":735087600,"approved_time":null}`
log.Println(string(b))
i.ApprovedTime = epoch.Time(time.Date(1993, 04, 17, 23, 0, 0, 0, time.UTC))
b, err = json.Marshal(i)
// prints `{"created_time":735087600,"approved_time":735087600}`
log.Println(string(b))
}