How to convert time.time to string in Golang?

Hi 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

Try it yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts