How to Convert Time to String in Golang

To convert time.Time to a string in Go, use the “Time.String()” method, which outputs the time in a default format, or “Time.Format()” method if you need a custom format.

Method 1: Using the time.String() function

In Go, you can use the time.String() method that returns a string representation of the time.Time value in a default format. The default format is equivalent to calling time.Format(time.RFC3339).

The Time.String() method returns the time formatted using the default format, which is:

Here’s an example demonstrating how to convert a time.Time value to a string using the String() method:

package main

import (
  "fmt"
  "time"
)

func main() {
  now := time.Now()

  timeStr := now.String()
  fmt.Printf("String time: %s\n", timeStr)
}

Output

String time: 2023-03-25 17:52:00.779816 +0530 IST m=+0.000070334

Method 2: Using the time.Format() function

In Golang, you can convert a time.Time value to a string using the time.Now().Format() method. The Format() method allows you to specify a layout string that determines the format of the output string.

package main

import (
  "fmt"
  "time"
)

func main() {
  timeStr := time.Now().Format("2006-01-02 15:04:05")
  fmt.Printf("Formatted String time: %v\n", timeStr)
}

Output

Formatted String time: 2023-03-25 17:48:01

Remember that the String() method’s output format is fixed and cannot be customized.

To format the time value according to a specific format, use the time.Now().Format() method.

That’s it!

Related posts

Golang time.Clock()

Golang time.Date()

Golang time.AddDate()