how to convert date to string in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert date to string in golang, use the String() method or Format() both will convert date time to string and return it.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows


Today, I will show you how do I convert date to string in golang, as mentioned above I’m going to use Time String() method or Format() method.

To use time String() method, we need time.Now() then we can apply String() method on it like time.Now().String()

To use time Format() method, we need time.Now() then we can apply Format() method on it like time.Now().Format("2006-01-02 15:04:05")

Let’s start our Golang convert date to string example

main.go

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Now()
	fmt.Println(t.String())
	fmt.Println(t.Format("2006-01-02 15:04:05"))
}

In the above example, we have converted a date time to a string and printed it in the console. let’s check the output.

Output

2022-08-20 11:07:38.176630166 +0000 UTC m=+0.000052847
2022-08-20 11:07:38

I hope it helps you, All the best 👍.

Follow me on Twitter