🐹 Go Time Handling Guide

Best practices for handling time in Go using the time package. Avoid common pitfalls and write robust time logic.

⚡ Quick Reference

✅ Do

  • • Use time.Time for all timestamps
  • • Store in UTC, display in local
  • • Use time.LoadLocation() for timezones
  • • Handle timezone loading errors
  • • Use time.Parse() with explicit layouts

❌ Don't

  • • Use Unix timestamps for storage
  • • Hardcode timezone offsets
  • • Ignore timezone loading errors
  • • Use time.Now() in tests
  • • Assume 24-hour days

🕐 Basic Time Operations

Creating and Formatting Times

🌍 Timezone Handling

Safe Timezone Operations

📝 Parsing and Validation

Robust Date Parsing

⏱️ Duration and Arithmetic

Safe Date Arithmetic

🧪 Testing Time Logic

Testable Time Code

⚠️ Common Pitfalls

Things That Will Bite You

1. Timezone Loading Errors

Always handle timezone loading errors - they can fail at runtime.

2. Layout String Confusion

Go uses a specific reference time for layouts: Mon Jan 2 15:04:05 MST 2006