Go by Example: Time Formatting / Parsing

The time package in Go provides several methods for formatting and parsing time values, making it easy to convert between human-readable string representations of times and the underlying Time type used by Go.

Here’s an example that demonstrates how to use the Format and Parse methods to format a time value as a string and parse a string back into a time value:

package main

import (
	"fmt"
	"time"
)

func main() {
	// Get the current time
	t := time.Now()
	fmt.Println("Current time:", t)

	// Format the time as a string using a predefined format
	formatted := t.Format(time.RFC3339)
	fmt.Println("Formatted time:", formatted)

	// Parse the formatted string back into a time value
	parsed, err := time.Parse(time.RFC3339, formatted)
	if err != nil {
		fmt.Println("Error parsing time:", err)
	} else {
		fmt.Println("Parsed time:", parsed)
	}
}

In this example, the time.Now function is used to get the current time, which is stored in the t variable. The Format method is then used to format the time as a string using the time.RFC3339 predefined format, which represents the time in a standardized ISO 8601 format. Finally, the Parse function is used to parse the formatted string back into a Time value, which is stored in the parsed variable.

The output of this program will be something like:

Current time: 2022-11-22 11:47:11.4444 +0100 CET
Formatted time: 2022-11-22T11:47:11+01:00
Parsed time: 2022-11-22 11:47:11 +0100 CET

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *