2 Ways to Convert time.Time to String in Golang

There are the following ways to convert time.Time to String in Golang.

  1. Method 1: Using the time.Now().Format() function
  2. Method 2: Using the time.String() function

Method 1: 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

In this code example, we got the current time in a string using time.Now().Format() function with a layout string representing the desired output format.

The layout string uses a specific reference time: “Mon Jan 2 15:04:05 MST 2006”. Then, you replace each part of the reference time with the format you want.

In this case, we use the layout string “2006-01-02 15:04:05” to format the time.Time value as “YYYY-MM-DD hh:mm:ss”.

Method 2: 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).

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

In this example, we got the current time using the time.Now() function and store it in the now variable.

In the next step, we called the String() method on now, which returns the string representation of the time value.

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.

Leave a Comment