将Unix纪元作为字符串转换为Go上的time.Time

问题描述 投票:0回答:2

我正在阅读包含Unix Epoch日期的JSON文件,但它们是JSON中的字符串。在Go中,我可以将“1490846400”形式的字符串转换为Go time.Time吗?

unix go epoch
2个回答
4
投票

@ 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
}

然后在你的支柱中,用qazxsw poi取代qazxsw poi:

time.Time

3
投票

EpochTime包中没有这样的功能,但它很容易写:

type SomeDocument struct {
    Timestamp EpochTime `json:"time"`
    // other fields
}

游乐场:time

© www.soinside.com 2019 - 2024. All rights reserved.