How to format a time.Time value as a string with a custom layout using strconv.FormatTime() in Golang?

In Go, the time package does not have a strconv.FormatTime() function. However, you can use the time.Time type's Format() method to format a time.Time value as a string with a custom layout.

Here's an example that demonstrates how to achieve this:

package main import ( "fmt" "time" ) func main() { // Create a time value now := time.Now() // Define a custom layout layout := "2006-01-02 15:04:05" // Format the time value using the custom layout str := now.Format(layout) // Print the formatted time string fmt.Println(str) }

In the above example, we:

  • Create a time.Time value named now, initialized with the current time.
  • Define a custom layout using a reference time of 2006-01-02 15:04:05. This reference time is chosen because it's the "zero" time in Go, meaning it will be represented as is in the output.
  • Use the now.Format(layout) method to format the now time value as a string using the custom layout.
  • Print the formatted time string.

You can modify the layout variable with different layouts defined in the time package's documentation to format the time.Time value according to your requirements.