Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UNIX timestamps in Golang
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
}
func (t *Timestamp) String() string {
return time.Time(*t).String()
}
@mcuadros

This comment has been minimized.

Copy link

mcuadros commented Mar 16, 2015

Embedding the time.Time structure you can use the Timetamp struct like the original one

type Timestamp struct {
    time.Time
}

func (t *Timestamp) MarshalJSON() ([]byte, error) {
    ts := t.Time.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.Time = time.Unix(int64(ts), 0)

    return nil
}
@evillemez

This comment has been minimized.

Copy link

evillemez commented Mar 4, 2016

Thank you for this... was writing the same thing and stumbled across this.

@mkraft

This comment has been minimized.

Copy link

mkraft commented Jan 18, 2017

👍

@cescoferraro

This comment has been minimized.

Copy link

cescoferraro commented Mar 15, 2018

func (t *Timestamp) Time() time.Time {
	return time.Time(*t)
}
@nuvi-wagner

This comment has been minimized.

Copy link

nuvi-wagner commented May 23, 2018

How do you then create a new instance of a Timestamp? Using the time.Now() method for example?

@NgocSon159

This comment has been minimized.

Copy link

NgocSon159 commented May 30, 2019

This function help me a lot! Thanks you so much.
func (t *Timestamp) SetBSON(raw bson.Raw) error {
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.