我在讀取一個包含Unix Epoch日期的JSON文件,但它們是JSON中的字符串。在Go中,我可以將形式爲「1490846400」的字符串轉換爲Go時間嗎?將Unix紀元作爲字符串轉換爲time.Time轉到
0
A
回答
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
}
2
沒有什麼不好,或不正確有關@ Ainar-G提供的答案,但有可能是更好的方式來做到這一點是與自定義JSON unmarshaler是:
type EpochTime time.Time
func (et *EpochTime) UnmarshalJSON(data []byte) error {
t := string.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
return nil
}
然後在你的結構,代之以time.Time
EpochTime
:
type SomeDocument struct {
Timestamp EpochTime `json:"time"`
// other fields
}
相關問題
- 1. Golang:將time.Time轉換爲字符串
- 2. 如何將HH:MM:SS字符串轉換爲UNIX紀元時間?
- 3. 如何將字符串轉換爲YYYY-MM-DD:HH:mm:SS:sss轉換爲紀元時間?
- 4. 將frame.time轉換爲紀元
- 5. INT - 字符串類型錯誤,同時將datetime轉換爲Unix時間紀元
- 6. 如何將字符串轉換爲紀元時間?
- 7. 在javascript中將UTC字符串轉換爲紀元時間
- 8. 如何將毫秒(hh:mm:ss.xxx)的字符串時間轉換爲time.Time?
- 9. 將字符串轉換爲int,int轉換爲字符串
- 10. 轉換DATETIME到Unix紀元Informix中
- 11. 將Jsoup元素轉換爲字符串
- 12. 將字符串轉換爲2元組
- 13. java將元素轉換爲字符串
- 14. 將字符串轉換爲「_」
- 15. 將字符串轉換爲
- 16. 將字符串轉換爲?
- 17. Java - 將Unix紀元時間轉換爲日期
- 18. Python 2.7將標準unix時間戳轉換爲紀元時間
- 19. 將QString Unix紀元時間轉換爲QString標準時間
- 20. 將UNIX紀元轉換爲日期對象
- 21. 將紀元後的秒數轉換爲unix時間
- 22. 將字符串轉換爲字符串
- 23. 將字符串轉換爲字符串
- 24. 將字符串轉換爲字符串
- 25. 將紀元時間轉換爲日期
- 26. 將mysql DATETIME列轉換爲紀元秒
- 27. OSX無法將ISO8601轉換爲紀元
- 28. 將HexNumber作爲字符串轉換爲字符串
- 29. 將字符串轉換日期(月,年)到了time.time
- 30. 將Unix時間戳轉換爲日期爲字符串? Swift
的可能的複製[如何解析在golang Unix時間戳(http://stackoverflow.com/questions/24987131/how-to-parse-unix-timestamp-in-golang) – Laurence