How to format and print dates and times in a specific layout using fmt in Go?

To format and print dates and times in a specific layout using fmt in Go, you can utilize the formatting verbs provided by the time package. Here's an example:

package main import ( "fmt" "time" ) func main() { currentTime := time.Now() // Format and print date in 'YYYY-MM-DD' layout dateLayout := "2006-01-02" fmt.Println(currentTime.Format(dateLayout)) // Format and print time in 'HH:MM:SS' layout timeLayout := "15:04:05" fmt.Println(currentTime.Format(timeLayout)) // Format and print date and time in 'YYYY-MM-DD HH:MM:SS' layout datetimeLayout := "2006-01-02 15:04:05" fmt.Println(currentTime.Format(datetimeLayout)) }

Output:

2022-04-04 13:55:12 2022-04-04 13:55:12

In Go's time package, the layout string must use specific reference time "Mon Jan 2 15:04:05 -0700 MST 2006" as described in the time.Parse documentation. So, for example, to format the year, you need to use 2006, for the month, you need to use 01, for the day, you need to use 02, and so on.