2017-04-15 52 views
0

我在讀取一個包含Unix Epoch日期的JSON文件,但它們是JSON中的字符串。在Go中,我可以將形式爲「1490846400」的字符串轉換爲Go時間嗎?將Unix紀元作爲字符串轉換爲time.Time轉到

+3

的可能的複製[如何解析在golang Unix時間戳(http://stackoverflow.com/questions/24987131/how-to-parse-unix-timestamp-in-golang) – Laurence

回答

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 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.TimeEpochTime

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