How to convert time.time to string in Golang?
December 07, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
In Go, you can convert a time.Time
value to a string by using the time.Time.Format()
method. This method takes a layout string that specifies the format of the resulting string, and returns a string that represents the time.Time
value in the specified format.
Here is an example of how to convert a time.Time
value to a string in Go:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
s := t.Format("2006-01-02 15:04:05")
fmt.Println(s)
}
In this example, we create a time.Time
value using the time.Now()
function and then use the time.Time.Format()
method to convert it to a string. The resulting string will be in the format “2006-01-02 15:04:05”, which is the layout string that we provided to the Format()
method.
You can use this technique to convert any time.Time
value to a string in Go. You can specify a different layout string to the Format()
method to control the format of the resulting string.
Output:
2022-12-10 09:42:18
All the best 👍