【问题标题】:Convert Unix epoch as a string to time.Time on Go将 Unix 纪元作为字符串转换为 time.Time on Go
【发布时间】:2017-09-11 20:45:42
【问题描述】:

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

【问题讨论】:

标签: unix go epoch


【解决方案1】:

time包中没有这个功能,但是写起来很简单:

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
}

游乐场:https://play.golang.org/p/2h0Vd7plgk.

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 2019-08-21
      • 2013-08-25
      • 2017-11-28
      • 2017-12-20
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多