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
andParseInLocation
functions for parsing date-time strings.
Example
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 anRFC-3339
date-time string. - We then use the
time.Parse
function to parse the date-time string into atime.Time
value. The first argument totime.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 atime.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 tot.Format
, we use thetime.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!
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go