I'm reading a JSON file that contains Unix Epoch dates, but they are strings in the JSON. In Go, can I convert a string in the form "1490846400" into a Go time.Time?
Asked
Active
Viewed 9,822 times
2 Answers
13
There is no such function in time
package, but it's easy to write:
func stringToTime(s string) (time.Time, error) {
sec, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(sec, 0), nil
}
Playground: https://play.golang.org/p/2h0Vd7plgk.

Ainar-G
- 34,563
- 13
- 93
- 119
7
There's nothing wrong, or incorrect about the answer provided by @Ainar-G, but likely a better way to do this is with a custom JSON unmarshaler:
type EpochTime time.Time
func (et *EpochTime) UnmarshalJSON(data []byte) error {
t := strings.Trim(string(data), `"`) // Remove quote marks from around the JSON string
sec, err := strconv.ParseInt(t, 10, 64)
if err != nil {
return err
}
epochTime := time.Unix(sec,0)
*et = EpochTime(epochTime)
return nil
}
Then in your struct, replace time.Time
with EpochTime
:
type SomeDocument struct {
Timestamp EpochTime `json:"time"`
// other fields
}

Jonathan Hall
- 75,165
- 16
- 143
- 189