codefx
codefx

Reputation: 10502

How to convert ISO 8601 time in golang?

What is the equivalent code in golang for the following shell command ? date -u +%Y-%m-%dT%T%z

Upvotes: 140

Views: 156609

Answers (5)

btubbs
btubbs

Reputation: 1875

ISO8601 allows for variable levels of granularity. You can have just a year, year+month, year+month+day, add a time portion, and optionally have a timezone portion. Go's built-in time parsing, however, requires you to know ahead-of-time which parts will be included.

The github.com/btubbs/datetime library provides a more flexible parser that can handle all the commonly used ISO8601 formats. See https://github.com/nav-inc/datetime

Disclosure: I wrote that library.

Upvotes: 8

cikenerd
cikenerd

Reputation: 2918

If you're looking for a simple, but not perfect solution consider using time.RFC3339 constant. But also know that there are differences between ISO8601 which are too complex for this answer.

See https://ijmacd.github.io/rfc3339-iso8601/ for differences and also has a handy test file generator to show differences. There is also a good discussion on SO here What's the difference between ISO 8601 and RFC 3339 Date Formats?

package main

import (
    "time"
    "fmt"
)

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

golang Time.Format

Upvotes: 277

dustinevan
dustinevan

Reputation: 977

Replacing the sign in the format with a Z triggers the ISO 8601 behavior. Which is exactly time.RFC3339. If you are wanting the string output to end in 'Z' what you need to do is convert to the UTC zone.

package main    
import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Now().UTC().Format("2006-01-02T15:04:05Z07:00"))
}
// this is the same format used by RFC3339. just a note on why. 

Upvotes: 7

avi.elkharrat
avi.elkharrat

Reputation: 6790

I had the following spec:

YYYY-MM-DDThh:mm:ss.sssZ

with the final Z being explicitly present in the examples.

Here's how I dealt with it:

  • first I found the time.RFCxxx that was the closest to my target
  • I copied its value
  • I fiddled with it until I found the expected result

which is

2006-01-02T15:04:05.999Z

Upvotes: 13

CrazyCrow
CrazyCrow

Reputation: 4235

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Now().UTC().Format("2006-01-02T15:04:05-0700"))
}

Upvotes: 57

Related Questions