How To Parse RFC-3339 / ISO-8601 date-time string in Go (Golang)

RFC-3339 is a standard for representing dates and times in a machine-readable format. It is widely used in the world of computing, and Go (Golang) provides built-in support for parsing RFC-3339 strings.

In this blog post, I will show you how to parse RFC-3339 strings in Golang. We will start by discussing the different formats that RFC-3339 supports, and then I will show you how to parse each format using the Golang time package. Everything can be done just by using the Go (Golang) standard library without having to install any third party tools or libraries.

RFC-3339 Formats

RFC-3339 supports a variety of formats for representing dates and times. The most common format is the following

2006-01-02T15:04:05Z

This format represents the date and time "January 2, 2006 at 3:04 PM UTC". The "Z" at the end of the string indicates that the time is in UTC.

RFC-3339 also supports a variety of other formats, including:

Parsing RFC-3339 Strings in Golang

To parse an RFC-3339 string in Golang, you can use the time.Parse() function. This function takes two arguments: the format of the string you want to parse, and the string itself.

func Parse(layout, value string) (Time, error)

You can use different pre-configured layouts, which you can find in the Go (Golang) standard library documentation page https://pkg.go.dev/time#pkg-constants

const (
  Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
  ANSIC       = "Mon Jan _2 15:04:05 2006"
  UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
  RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
  RFC822      = "02 Jan 06 15:04 MST"
  RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
  RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
  RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
  RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
  RFC3339     = "2006-01-02T15:04:05Z07:00"
  RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
  Kitchen     = "3:04PM" 	// Handy time stamps.
  Stamp      = "Jan _2 15:04:05"
  StampMilli = "Jan _2 15:04:05.000"
  StampMicro = "Jan _2 15:04:05.000000"
  StampNano  = "Jan _2 15:04:05.000000000"
  DateTime   = "2006-01-02 15:04:05"
  DateOnly   = "2006-01-02"
  TimeOnly   = "15:04:05"
)

For example, to parse the string 2023-05-02T09:34:01Z, you would use the following code

package main

import (
	"fmt"
	"time"
)

func main() {
	t, err := time.Parse(time.RFC3339, "2023-05-02T09:34:01Z")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(t)
}

This will generate the following output

2023-05-02 09:34:01 +0000 UTC

You can also run this snippet on the Golang Playground https://go.dev/play/p/JJk20oIJJFO

Join the Golang Developers Community on Golang Cafe