Search code examples
javascriptgotimeiso

Javascript toISOString time in Golang


I'm trying to generate ISO 8601 timestamp in Golang.

Doing

time.Now().UTC().Format(time.RFC3339)
//2016-04-12T19:32:20Z

in Javascript

new Date().toISOString()
//2016-04-12T19:46:47.286Z

It appears the only difference is in JavaScript the time reports milliseconds, while Golang it produces it in seconds. I'd like to try and get these to be the same.

I've looked at time.RFC3339Nano

But that produces too much precision 2016-04-12T19:35:16.341032697Z

How can I get Golang to produce time that is equivalent to JavaScript's toISOString()?


Solution

  • From looking in pkg/time where the constants are defined

    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    

    From the documentation:

    The reference time used in the layouts is the specific time: Mon Jan 2 15:04:05 MST 2006

    To define your own format, write down what the reference time would look like formatted your way;

    It should be something like so:

    JavascriptISOString := "2006-01-02T15:04:05.999Z07:00"
    time.Now().UTC().Format(JavascriptISOString)