How to format time in Go/Golang
You can read original(with syntax highlighting) article on
Go uses a special "magic" reference time that might seem weird at first:
The Magic Reference Time is: 01/02 03:04:05PM 2006 MST
Or put another way: January 2, 2006 at 3:04:05 PM MST
Here's the genius part - the numbers in this date line up in order:
- Month: 1
- Day: 2
- Hour: 3
- Minute: 4
- Second: 5
- Year: 6
Let me show you with a super simple cheat sheet:
The trick to remember:
- It's all based on one specific time: January 2, 2006 at 3:04:05 PM
- Just write the date/time exactly how you want it to look, but use the reference time's numbers
Some easy examples:
Pro Tips:
- Need 24-hour time? Use "15" for hours
- Need 12-hour time? Use "3" for hours
- Need PM/AM? Just write "PM" or "pm" where you want it
- Need month name? Use "January" or "Jan"
Think of it like a template - you're just showing Go how you want the date to look, using that special reference date as your model!
Now let's see how to handle timezones:
If we don't pay attention to the timezones, we can easily get wrong results.
Here are the GOLDEN RULES for server timezone handling:
IMPORTANT TIPS:
- Always store UTC in your database
- Always use UTC for internal server operations
- Only convert to specific timezones when displaying to users
- Use RFC3339 for API responses
- Be explicit about timezone in logs
Official documentation for time in Go: https://pkg.go.dev/time
👍