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 👍.

Try it Yourself

Premium Content

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

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

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.

Related Posts