Saturday, November 2, 2024
HomeGolangConvert date or time to string in Go (Golang)

Convert date or time to string in Go (Golang)



To transform time.Time to a string in Go, you need to use the Time.String() technique, which outputs the time in a default format, or Time.Format() technique in case you want a customized format.

Take a look at the instance under the place we convert the present time in UTC timezone: t := time.Now().UTC() to a string. The s1 string is created by calling the t.String() technique, and as you’ll be able to see within the output, it’s formatted utilizing the default format: 2006-01-02 15:04:05.999999999 -0700 MST. Alternatively, the second string s2 is formatted by t.Format() technique with the year-month-day format as an argument: 2006-01-02.

If you’re unfamiliar with the Go time format structure, additionally known as the reference time, take a look at our cheatsheet about date and time format in Go.

bundle principal

import (
    "fmt"
    "time"
)

func principal() {
    t := time.Now().UTC()
    s1 := t.String()
    fmt.Printf("s1: %sn", s1)

    s2 := t.Format("2006-01-02")
    fmt.Printf("s2: %sn", s2)
}

Output:

s1: 2022-12-13 05:32:03.27335197 +0000 UTC
s2: 2022-12-13
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments