To convert time.Time
to a string in Go, you can use the Time.String()
method, which outputs the time in a default format, or Time.Format()
method if you need a custom format.
Look at the example below where we convert the current time in UTC timezone: t := time.Now().UTC()
to a string. The s1
string is created by calling the t.String()
method, and as you can see in the output, it is formatted using the default format: 2006-01-02 15:04:05.999999999 -0700 MST
. On the other hand, the second string s2
is formatted by t.Format()
method with the year-month-day format as an argument: 2006-01-02
.
If you are unfamiliar with the Go time format layout, also called the reference time, check out our cheatsheet about date and time format in Go.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now().UTC()
s1 := t.String()
fmt.Printf("s1: %s\n", s1)
s2 := t.Format("2006-01-02")
fmt.Printf("s2: %s\n", s2)
}
Output:
s1: 2022-12-13 05:32:03.27335197 +0000 UTC
s2: 2022-12-13