How to Format Date and Time With Go Language

In Golang on 2~4 minutes
How to Format Date and Time With Go Language

Date and time formatting with Golang can be quite confusing due to its weird formatting patterns. But there are some easy methods that instantly give you full control of handling date and time with Go language.

First, install Go language and create a new Go project if you have not yet created one.

Time Formatting

The following code will print the current unformatted time.

t := time.Now()

fmt.Println(t)  // 2022-01-06 00:00:00 +0000 UTC m=+0.000000001

Seconds

The following methods can be used to get the current second.

t := time.Now()

fmt.Println(t.Format("05"))
fmt.Println(t.Second())

Minutes

The following methods will print the current minute.

t := time.Now()

fmt.Println(t.Format("04"))
fmt.Println(t.Minute())

Hours

The following codes will print the current hour in both 12 and 24-hour formats.

t := time.Now()

fmt.Println(t.Format("03"))  // 12 hours
fmt.Println(t.Format("15"))  // 24 hours
fmt.Println(t.Hour())        // 24 hours

Date Formatting

Day

The following code will print the current day in both short and long formats, such as “Sun” and “Sunday”.

t := time.Now()

fmt.Println(t.Format("Mon"))
fmt.Println(t.Format("Monday"))

Date

The following code will print the current date, such as 05, 18, 24.

t := time.Now()

fmt.Println(t.Day())

Month

The following code will print the current month as a number and full month name.

t := time.Now()

fmt.Println(t.Format("01"))
fmt.Println(t.Month())

Year

The following code will print the current year in both short and long formats.

t := time.Now()

fmt.Println(t.Format("06"))    // 08
fmt.Println(t.Format("2006"))  // 2010
fmt.Println(t.Year())          // 2022

We can use combinations of previously used methods to re-create popular date and time formats.

Hour, Minute And Second

The following code will print the current time in the Hour:Minute:Second format.

t := time.Now()

fmt.Println(t.Format("15:04:05"))

Year, Month And Date

The following code will print the current date in Date-Month-Year and Year-Month-Date formats.

t := time.Now()

fmt.Println(t.Format("02-01-2006"))
fmt.Println(t.Format("2006-01-02"))

Time-Zone Adjustment

We can use the LoadLocation() method to offset the timezone.

t := time.Now()
location, err := time.LoadLocation("UTC")

if err != nil {
	return
}

fmt.Println(t.In(location).Format("2006-01-02 15:04:05"))

Visit pkg.go.dev/time for more information about the Go Time package.