How to format and parse date and time in Go?

In Go, the time package provides functions to format and parse date and time values. Here's an example of formatting and parsing date and time in Go:

  1. Formatting Date and Time:
package main import ( "fmt" "time" ) func main() { // Get the current date and time currentTime := time.Now() // Format the date and time using a layout formattedTime := currentTime.Format("2006-01-02 15:04:05") fmt.Println("Formatted time:", formattedTime) }

Output:

Formatted time: 2021-12-31 23:59:59

In the above code, time.Now() returns the current date and time. The Format() function is used to format the date and time using a layout string. The layout string must be in a specific format and can include a combination of predefined constants and your own format.

  1. Parsing Date and Time:
package main import ( "fmt" "time" ) func main() { // Define a date and time string to parse dateTimeString := "2021-12-31 23:59:59" // Parse the date and time string using the specified layout parsedTime, _ := time.Parse("2006-01-02 15:04:05", dateTimeString) fmt.Println("Parsed time:", parsedTime) }

Output:

Parsed time: 2021-12-31 23:59:59 +0000 UTC

In the above code, we define a date and time string to parse (dateTimeString). The Parse() function is then used to parse the date and time string using the specified layout string. The layout string must match the format of the date and time string.

Note: The second return value of the time.Parse() function is an error value which can be used to handle any parsing errors. In the example above, we ignore the error using _, but in your actual code, you should handle the error appropriately.

These examples should give you a basic understanding of how to format and parse date and time in Go using the time package. Make sure to refer to the Go documentation for more details on available predefined layouts and additional formatting options.