Created
May 1, 2015 19:38
-
-
Save dmlyons/0c14c6155c6e8cba9ec4 to your computer and use it in GitHub Desktop.
A type to use time.Time and quoted numerical timestamps with json marshal/unmarshal
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 main | |
// Liberally used https://medium.com/coding-and-deploying-in-the-cloud/time-stamps-in-golang-abcaf581b72f | |
import ( | |
"encoding/json" | |
"fmt" | |
"strconv" | |
"time" | |
) | |
type myStruct struct { | |
Ts QuotedTimestamp `json:"ts,string"` | |
} | |
type QuotedTimestamp time.Time | |
func (t *QuotedTimestamp) Time() time.Time { | |
return time.Time(*t) | |
} | |
func (t *QuotedTimestamp) MarshalJSON() ([]byte, error) { | |
ts := time.Time(*t).Unix() | |
stamp := fmt.Sprint(ts) | |
return []byte(`"`+stamp+`"`), nil | |
} | |
func (t *QuotedTimestamp) UnmarshalJSON(b []byte) error { | |
ts, err := strconv.Atoi(string(b)) | |
if err != nil { | |
return err | |
} | |
*t = QuotedTimestamp(time.Unix(int64(ts), 0)) | |
return nil | |
} | |
func main() { | |
j := []byte(`{"ts": "1430502363"}`) | |
var m myStruct | |
_ = json.Unmarshal(j, &m) | |
fmt.Println(m.Ts.Time().Format("Mon Jan 2 15:04:05 -0700 MST 2006")) | |
newJ, _ := json.MarshalIndent(&m, "", "") | |
fmt.Println(string(newJ)) | |
time.Sleep(1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment