How to format time in Go/Golang

How to format time in Go/Golang

You can read original(with syntax highlighting) article on

https://www.tural.pro/blogs/how-to-format-time-in-go-golang


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:

  1. It's all based on one specific time: January 2, 2006 at 3:04:05 PM
  2. 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

https://www.turalasgarov.com/


To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics