Skip to content

Instantly share code, notes, and snippets.

@akhrszk
Created October 21, 2020 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akhrszk/8ae5be4df99ecd8956ab07d22841ec2e to your computer and use it in GitHub Desktop.
Save akhrszk/8ae5be4df99ecd8956ab07d22841ec2e to your computer and use it in GitHub Desktop.
unix timestamp in Golang
// marshal/unmarshal to/from unix timestamp
// implement the Scanner and Valuer interfaces of gorm (https://gorm.io/docs/data_types.html)
package custom
import (
"time"
"fmt"
"strconv"
"database/sql/driver"
)
type Timestamp time.Time
func (t *Timestamp) MarshalJSON() ([]byte, error) {
unixTimestamp := fmt.Sprintf("\"%d\"", time.Time(*t).Unix())
return []byte(unixTimestamp), nil
}
func (t *Timestamp) UnmarshalJSON(data []byte) error {
unixTimestamp, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
return err
}
*t = Timestamp(time.Unix(unixTimestamp, 0))
return nil
}
func (t *Timestamp) Scan(value interface{}) error {
time, ok := value.(time.Time)
if ok {
*t = Timestamp(time)
}
return nil
}
func (t Timestamp) Value() (driver.Value, error) {
return time.Time(t), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment