Last active
December 25, 2016 13:19
-
-
Save benzsuankularb/159511922798b8f7e5a0276027f51570 to your computer and use it in GitHub Desktop.
Timestamp for marshal/unmarshal json from javascript timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package timestamp | |
import ( | |
"strconv" | |
"time" | |
) | |
// Declare as *Timestamp to get it worked else it will use default time string format. | |
type Timestamp struct { | |
time.Time | |
} | |
func (t *Timestamp) MarshalJSON() ([]byte, error) { | |
ts := t.Time.UnixNano() / 1000 | |
return []byte(strconv.Itoa(int(ts))), nil | |
} | |
func (t *Timestamp) UnmarshalJSON(b []byte) error { | |
ts, err := strconv.Atoi(string(b)) | |
if err != nil { | |
return err | |
} | |
ts64 := int64(ts) | |
t.Time = time.Unix(ts64/int64(time.Millisecond), ts64%int64(time.Millisecond)*1000) | |
return nil | |
} | |
func (t *Timestamp) IsZero() bool { | |
return t.Second() == 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment