Cookies management by TermsFeed Cookie Consent

📝 Convert date or time to string in Go

shorts introduction time

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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

✨ 5 different ways to loop over a time.Ticker in Go

Learn how to use the popular time.Ticker struct in loops
introduction time

🐾 How to compare strings in Go

shorts introduction strings

🛑 Exit an app in Go

shorts introduction os