I've got a string with milliseconds since the epoch (it came originally from a java.lang.System.currentTimeMillis()
call). What's the right way to convert this string into a human readable timestamp string in Go?
Looking at the time package I see the Parse
function, but the layouts all seem to be normal timezone-based times. Once into a Time object, I can use Format(Time.Stamp)
to get the output I want, but I'm not clear on how to get the string into a Time object.
How to parse datetime in Go. Parse is a function that accepts a string layout and a string value as arguments. Parse parses the value using the provided layout and returns the Time object it represents. It returns an error if the string value specified is not a valid datetime.
In Go lang, how to get the epoch timestamp, the number of seconds passed since the epoch? If you would convert a time string to epoch timestamp, you can first parse the time string and then use the Unix() function to convert it into an epoch timestamp as follows.
The Unix epoch is at the beginning of 1970 meaning that any timestamp prior to 1970 needs to be represented as a negative number representing the number of seconds until January 1st, 1970 00:00:00 UTC.
The format string does not support milliseconds since the epoch, so you need to parse manually. For example:
func msToTime(ms string) (time.Time, error) {
msInt, err := strconv.ParseInt(ms, 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(0, msInt*int64(time.Millisecond)), nil
}
Check out http://play.golang.org/p/M1dWGLT8XE to play with the example live.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With