How to get RFC 3339 formatted datetime in string value with millisecond precision in GO lang

186 Views Asked by At

I want to get current time in UTC in RFC 3339 format (string value) with millisecond precision in GO lang.

Ex. "timestamp": "2023-10-18T20:43:20.542Z".
but i am getting  2009-11-10T23:00:00Z

I looked at a link which mentioned "Rather than add more inconsistency, it seems like t.Round(time.Millisecond).Format(time.RFC3339Nano) is very clear and equivalent to what we'd provide with an explicit RFC3339Milli.".

https://github.com/golang/go/issues/36472 where they mentioned to use

I tried some format but i did not get what i am looking for. Am i doing anything wrong ? https://go.dev/play/p/Dmxkte9sAEz

1

There are 1 best solutions below

1
On

I was able to get what i was looking for. I am in different locale and playground provided UTC time so there was difference in format from playground and my code(I had missed to get UTC time).

First get the time in UTC format and then provide format which will provide and it works.

package main

import (
    "fmt"
    "time"
)

const timeFormatRFC3339Milli = "2006-01-02T15:04:05.000Z07:00"

func main() {
    fmt.Println(time.Now().UTC().Format(timeFormatRFC3339Milli))
}