Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a milliseconds-since-epoch timestamp string in Go?

Tags:

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.

like image 344
P.T. Avatar asked Nov 08 '12 17:11

P.T.


People also ask

How do you parse time in go?

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.

What is the syntax to get the epoch timestamp in go?

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.

Is epoch milliseconds or seconds?

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.


1 Answers

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.

like image 99
Stephen Weinberg Avatar answered Oct 20 '22 08:10

Stephen Weinberg