Skip to content

Instantly share code, notes, and snippets.

@skarllot
Forked from bsphere/timestamp.go
Last active May 23, 2017 13:23
Show Gist options
  • Save skarllot/9b22cae3aa2377a280bb to your computer and use it in GitHub Desktop.
Save skarllot/9b22cae3aa2377a280bb to your computer and use it in GitHub Desktop.
A Time type that (un)marshal from/to unix timing
package timestamp
import (
"fmt"
"gopkg.in/mgo.v2/bson"
"strconv"
"time"
)
type Timestamp time.Time
func (t *Timestamp) MarshalJSON() ([]byte, error) {
ts := time.Time(*t).Unix()
stamp := fmt.Sprint(ts)
return []byte(stamp), nil
}
func (t *Timestamp) UnmarshalJSON(b []byte) error {
ts, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
*t = Timestamp(time.Unix(ts, 0))
return nil
}
func (t Timestamp) GetBSON() (interface{}, error) {
if time.Time(*t).IsZero() {
return nil, nil
}
return time.Time(*t), nil
}
func (t *Timestamp) SetBSON(raw bson.Raw) error {
var tm time.Time
if err := raw.Unmarshal(&tm); err != nil {
return err
}
*t = Timestamp(tm)
return nil
}
func (t *Timestamp) String() string {
return time.Time(*t).String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment