0
0
GoHow-ToBeginner · 3 min read

How to Format Time in Go: Syntax and Examples

In Go, you format time using the Format method on a time.Time object with a layout string that represents the reference time Mon Jan 2 15:04:05 MST 2006. This layout defines the output format by example, not by format codes.
📐

Syntax

Use the Format method on a time.Time value with a layout string. The layout string must be the exact representation of the reference time Mon Jan 2 15:04:05 MST 2006 in the desired output format.

  • timeValue.Format(layout string): formats the time according to the layout.
  • The layout uses the reference time's values to specify the format.
go
formattedTime := timeValue.Format("2006-01-02 15:04:05")
💻

Example

This example shows how to get the current time and format it as a string in the format YYYY-MM-DD HH:MM:SS.

go
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	formatted := now.Format("2006-01-02 15:04:05")
	fmt.Println("Current time formatted:", formatted)
}
Output
Current time formatted: 2024-06-15 14:30:45
⚠️

Common Pitfalls

Many beginners try to use format codes like YYYY or MM like in other languages, but Go requires the exact reference time values.

Also, the layout must be a string literal matching the reference time's values, not a date format pattern.

go
package main

import (
	"fmt"
	"time"
)

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

	// Wrong: using format codes like other languages
	// formattedWrong := now.Format("YYYY-MM-DD HH:mm:ss") // This will output the literal string

	// Right: use Go's reference time layout
	formattedRight := now.Format("2006-01-02 15:04:05")

	fmt.Println("Wrong format (literal):", "YYYY-MM-DD HH:mm:ss")
	fmt.Println("Correct format:", formattedRight)
}
Output
Wrong format (literal): YYYY-MM-DD HH:mm:ss Correct format: 2024-06-15 14:30:45
📊

Quick Reference

Here are some common layout parts and their meanings based on the reference time:

Layout PartMeaningExample Output
2006Year2024
01Month (zero-padded)06
02Day (zero-padded)15
15Hour (24-hour)14
03Hour (12-hour)02
04Minute30
05Second45
PMAM/PM markerPM
MSTTime zone abbreviationMST

Key Takeaways

Use the exact reference time "Mon Jan 2 15:04:05 MST 2006" as the layout string to format time in Go.
Do not use common format codes like YYYY or MM; Go uses the reference time's values instead.
The Format method returns a string representing the time in the specified layout.
Remember that the layout string is an example time, not a pattern.
Use the time package's Format method on a time.Time value to get formatted time.