我正在阅读包含Unix Epoch日期的JSON文件,但它们是JSON中的字符串。在Go中,我可以将“1490846400”形式的字符串转换为Go time.Time吗?
答案 0 :(得分:3)
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
}
包中没有这样的功能,但写起来很容易:
{{1}}
答案 1 :(得分:3)
@ Ainar-G提供的答案没有错误或错误,但更好的方法是使用自定义JSON解组器:
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
}
然后在您的结构中,将time.Time
替换为EpochTime
:
type SomeDocument struct {
Timestamp EpochTime `json:"time"`
// other fields
}