Skip to content

A wrapper around time.Time that serializes as epoch seconds. Also provides a nullable counterpart and SQL support.

License

Notifications You must be signed in to change notification settings

hanakoa/epoch-time

Repository files navigation

epoch-time

GoDoc Go report CircleCI Coverage Status GitHub Release

This library offers a timestamp struct that is SQL-compatible and marshals/unmarshals as epoch seconds. It also offers a nullable version.

Why?

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.

Usage

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))
}

About

A wrapper around time.Time that serializes as epoch seconds. Also provides a nullable counterpart and SQL support.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages