How to Parse Unix Timestamps
Parsing Unix timestamps in Go may seem like a simple task, but it can lead to unexpected errors. When attempting to parse a timestamp using time.Parse, you may encounter an out of range error even if the layout appears to be correct.
The reason for this is that time.Parse does not handle Unix timestamps. Instead, you should use the strconv.ParseInt function to convert the timestamp string to an int64 and then use the time.Unix function to create a time.Time object.
Here's an example:
package main import ( "fmt" "time" "strconv" ) func main() { i, err := strconv.ParseInt("1405544146", 10, 64) if err != nil { panic(err) } tm := time.Unix(i, 0) fmt.Println(tm) }
This code will output the correct timestamp:
2014-07-16 20:55:46 +0000 UTC
Important Note:
In the original example, strconv.Atoi was used instead of strconv.ParseInt. However, strconv.Atoi can result in integer overflows on 32-bit systems. Therefore, strconv.ParseInt is recommended to handle all cases safely.
The above is the detailed content of How to Safely Parse Unix Timestamps in Go?. For more information, please follow other related articles on the PHP Chinese website!