7

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()?

RamenChef
  • 5,557
  • 11
  • 31
  • 43
K2xL
  • 9,730
  • 18
  • 64
  • 101

1 Answers1

14

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)
matt.s
  • 1,698
  • 1
  • 20
  • 29
  • works great. strange that go doesn't have something like `RFC3339Milli` or something defined.. they go from seconds to nanoseconds – K2xL Apr 12 '16 at 20:59
  • 2
    You're right, but the language designers tend to look for a minimum set (even if it sometimes excludes useful stuff). At least it is pretty easy to make on your own. – matt.s Apr 12 '16 at 21:00