Parsing RFC-3339 / ISO-8601 date-time string in Go By Example

Go: Parsing RFC-3339 / ISO-8601 date-time string

In Go, you can parse RFC-3339 / ISO-8601 date-time strings using the time package. The time package provides the Parse and ParseInLocation functions for parsing date-time strings.

Example

Run Code

package main

import (
    "fmt"
    "time"
)

func main() {
    // RFC-3339 date-time string
    dateStr := "2023-04-02T12:30:45.123Z"

    // Parse RFC-3339 date-time string
    t, err := time.Parse(time.RFC3339Nano, dateStr)
    if err != nil {
        panic(err)
    }

    // Print the time in different formats
    fmt.Println(t.Format(time.RFC1123))               // Sun, 02 Apr 2023 12:30:45 UTC
    fmt.Println(t.Format("2006-01-02 15:04:05.000000")) // 2023-04-02 12:30:45.123000
}

Explaination

  • In above example, we define a string dateStr that represents an RFC-3339 date-time string.
  • We then use the time.Parse function to parse the date-time string into a time.Time value. The first argument to time.Parse specifies the layout of the input date-time string. In this case, we use the time.RFC3339Nano layout, which supports date-time strings in RFC-3339 format with nanosecond precision.
  • If the parsing is successful, time.Parse returns a time.Time value representing the parsed date-time.
  • Finally, we use the t.Format function to print the parsed date-time in different formats. In the first call to t.Format, we use the time.RFC1123 layout to format the date-time string in a standard format. In the second call, we use a custom layout to format the date-time string in a specific format.

I hope this example helps you parse RFC-3339 / ISO-8601 date-time strings in Go!