Skip to content

Instantly share code, notes, and snippets.

@bsphere
Last active January 23, 2024 02:50
Show Gist options
  • Save bsphere/8369aca6dde3e7b4392c to your computer and use it in GitHub Desktop.
Save bsphere/8369aca6dde3e7b4392c to your computer and use it in GitHub Desktop.

Revisions

  1. bsphere revised this gist Sep 16, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion timestamp.go
    Original file line number Diff line number Diff line change
    @@ -27,7 +27,7 @@ func (t *Timestamp) UnmarshalJSON(b []byte) error {
    return nil
    }

    func (t *Timestamp) GetBSON() (interface{}, error) {
    func (t Timestamp) GetBSON() (interface{}, error) {
    if time.Time(*t).IsZero() {
    return nil, nil
    }
  2. bsphere revised this gist Sep 5, 2014. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions timestamp.go
    Original file line number Diff line number Diff line change
    @@ -46,3 +46,7 @@ func (t *Timestamp) SetBSON(raw bson.Raw) error {

    return nil
    }

    func (t *Timestamp) String() string {
    return time.Time(*t).String()
    }
  3. bsphere renamed this gist Sep 5, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. bsphere created this gist Sep 5, 2014.
    48 changes: 48 additions & 0 deletions gistfile1.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    package timestamp

    import (
    "fmt"
    "labix.org/v2/mgo/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.Atoi(string(b))
    if err != nil {
    return err
    }

    *t = Timestamp(time.Unix(int64(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
    }