How do I format a time value using the time.Format() method in Go?
Jun 23, 2025 am 12:50 AMGo's time.Format() method formats the time string through the reference time Mon Jan 2 15:04:05 MST 2006, and replaces the corresponding part in the template with specific values. For example: "2006" for the year, "01" for the month, "02" for daily use, "15" for the hour (24-hour system), "04" for the minute, "05" for the second, and "MST" for the time zone; common formats such as "2006-01-02 15:04:05" represent the complete date and time, and static text such as "The date is: 2006-01-02" can be added; common errors include using YYYY-MM-DD or HH, and you need to pay attention to the correct handling of upper and lower case, spaces and time zone information.
In Go, the time.Format()
method is used to format a time value into a specific string representation. The trick is that it doesn't use regular format specifiers like other languages ??— instead, you use a reference time.
The magic date and time used as a template is:
Mon Jan 2 15:04:05 MST 2006
If you remember that one line, you're most of the way there.
Understanding How time.Format()
Works
Go uses a unique approach for formatting dates. Instead of using format strings with %Y-%m-%d
or similar, it uses an example time — the one above — and replaces each part with what you want in your output.
For example:
- To get just the year, you'd use
"2006"
- For a full date like
2024-04-05
, you'd write"2006-01-02"
It's case-sensitive and spacing matters, so be precise.
Here's how some common components map:
- Year →
2006
- Month (numeric) →
01
- Day →
02
- Hour (24-hour format) →
15
- Minute →
04
- Second →
05
- Timezone →
MST
So if you want to format a time like 2024-04-05 14:30:00
, your layout would be "2006-01-02 15:04:05"
.
Practical Examples of Formatting Time
Let's say you have a time.Time
value and you want to display it differently based on your needs.
Basic date and time:
now := time.Now() formatted := now.Format("2006-01-02 15:04:05") // Output might look like: "2024-04-05 13:45:30"
Only the date:
formatted := now.Format("2006-01-02") // Output: "2024-04-05"
Time with AM/PM:
formatted := now.Format("3:04 PM") // Output: "1:45 PM"
You can also include static text around the formatted parts by wrapping them in quotes:
formatted := now.Format("The date is: 2006-01-02") // Output: "The date is: 2024-04-05"
Common Mistakes to Avoid
One of the most common mistakes when using time.Format()
is mixing up the reference values. For instance:
- Using
YYYY-MM-DD
instead of2006-01-02
- Forgetting that hour is
15
for 24-hour format, notHH
Also, keep in mind:
- The reference time is in MST timezone, which is UTC-7 without daylight saving
- If you're printing the timezone, make sure your time object has location info
- Whitespace and punctuation must match exactly what you want in the output
A few gotchas:
-
"Jan"
gives short month names like "Apr","January"
gives full names like "April" -
"02"
ensures leading zeros for days;"2"
will work but won't pad single digits -
"04"
for minutes and"05"
for seconds are easy to mix up
That's basically how time.Format()
works in Go. It's different from what you might expect at first, but once you get used to the reference time pattern, it becomes second nature.
The above is the detailed content of How do I format a time value using the time.Format() method in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

Usecontexttopropagatecancellationanddeadlinesacrossgoroutines,enablingcooperativecancellationinHTTPservers,backgroundtasks,andchainedcalls.2.Withcontext.WithCancel(),createacancellablecontextandcallcancel()tosignaltermination,alwaysdeferringcancel()t

Use a dedicated and reasonably configured HTTP client to set timeout and connection pools to improve performance and resource utilization; 2. Implement a retry mechanism with exponential backoff and jitter, only retry for 5xx, network errors and 429 status codes, and comply with Retry-After headers; 3. Use caches for static data such as user information (such as sync.Map or Redis), set reasonable TTL to avoid repeated requests; 4. Use semaphore or rate.Limiter to limit concurrency and request rates to prevent current limit or blocking; 5. Encapsulate the API as an interface to facilitate testing, mocking, and adding logs, tracking and other middleware; 6. Monitor request duration, error rate, status code and retry times through structured logs and indicators, combined with Op

To correctly copy slices in Go, you must create a new underlying array instead of directly assigning values; 1. Use make and copy functions: dst:=make([]T,len(src));copy(dst,src); 2. Use append and nil slices: dst:=append([]T(nil),src...); both methods can realize element-level copying, avoid sharing the underlying array, and ensure that modifications do not affect each other. Direct assignment of dst=src will cause both to refer to the same array and are not real copying.

Use the template.ParseFS and embed package to compile HTML templates into binary files. 1. Import the embed package and embed the template file into the embed.FS variable with //go:embedtemplates/.html; 2. Call template.Must(template.ParseFS(templateFS,"templates/.html")))) to parse all matching template files; 3. Render the specified in the HTTP processor through tmpl.ExecuteTemplate(w,"home.html", nil)

AruneinGoisaUnicodecodepointrepresentedasanint32,usedtocorrectlyhandleinternationalcharacters;1.Userunesinsteadofbytestoavoidsplittingmulti-byteUnicodecharacters;2.Loopoverstringswithrangetogetrunes,notbytes;3.Convertastringto[]runetosafelymanipulate

Go uses time.Time structure to process dates and times, 1. Format and parse the reference time "2006-01-0215:04:05" corresponding to "MonJan215:04:05MST2006", 2. Use time.Date(year, month, day, hour, min, sec, nsec, loc) to create the date and specify the time zone such as time.UTC, 3. Time zone processing uses time.LoadLocation to load the position and use time.ParseInLocation to parse the time with time zone, 4. Time operation uses Add, AddDate and Sub methods to add and subtract and calculate the interval.

To import local packages correctly, you need to use the Go module and follow the principle of matching directory structure with import paths. 1. Use gomodinit to initialize the module, such as gomodinitexample.com/myproject; 2. Place the local package in a subdirectory, such as mypkg/utils.go, and the package is declared as packagemypkg; 3. Import it in main.go through the full module path, such as import "example.com/myproject/mypkg"; 4. Avoid relative import, path mismatch or naming conflicts; 5. Use replace directive for packages outside the module. Just make sure the module is initialized
