Understanding Time and Duration in Golang with Real Examples
3 min read
Working with time in Go is pretty straightforward once you get the hang of it. Go’s standard library provides a powerful time
package that lets you do everything—from checking the current time, calculating durations, formatting dates, to even parsing strings into time.
In this article, we’ll go through:
Getting the current time
Working with
Duration
Adding and subtracting time
Formatting and parsing time
Sleeping and timers
1. Getting the Current Time
To get the current time in Go, you can use time.Now()
.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("Current Time:", now)
}
Sample Output:
Current Time: 2025-04-09 13:45:00.123456789 +0530 IST
You can get parts of the time using methods like:
fmt.Println("Year:", now.Year())
fmt.Println("Month:", now.Month())
fmt.Println("Day:", now.Day())
fmt.Println("Hour:", now.Hour())
2. What is time.Duration
?
time.Duration
represents the difference between two time.Time
values. It’s internally stored as nanoseconds, but we usually use helpers like time.Second
, time.Minute
, etc.
duration := 2 * time.Hour
fmt.Println("Duration in hours:", duration.Hours())
You can create custom durations like:
myDuration := time.Duration(90) * time.Minute
fmt.Println("My Duration:", myDuration)
3. Adding and Subtracting Time
Add 1 hour and 30 minutes:
future := time.Now().Add(1*time.Hour + 30*time.Minute)
fmt.Println("Future Time:", future)
Subtract 1 day:
past := time.Now().Add(-24 * time.Hour)
fmt.Println("Yesterday:", past)
Time difference:
t1 := time.Now()
t2 := t1.Add(2*time.Hour + 10*time.Minute)
diff := t2.Sub(t1)
fmt.Println("Difference:", diff)
4. Formatting Time in Go
Go uses a weird but fixed layout to format time:
"Mon Jan 2 15:04:05 MST 2006"
Yes, that’s the actual reference time.
now := time.Now()
formatted := now.Format("2006-01-02 15:04:05")
fmt.Println("Formatted Time:", formatted)
More examples:
fmt.Println("Date Only:", now.Format("02 Jan 2006"))
fmt.Println("Time Only:", now.Format("03:04 PM"))
5. Parsing Strings into Time
To convert a string into time.Time
:
layout := "2006-01-02 15:04:05"
str := "2025-04-09 10:30:00"
parsedTime, err := time.Parse(layout, str)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Parsed Time:", parsedTime)
}
6. Sleep and Timers
Pause execution:
fmt.Println("Sleeping for 2 seconds...")
time.Sleep(2 * time.Second)
fmt.Println("Awake!")
Using time.After
:
ch := time.After(3 * time.Second)
fmt.Println("Waiting...")
<-ch
fmt.Println("3 seconds passed.")
7. Tickers for Repeated Tasks
Tickers run something on intervals:
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for i := 0; i < 5; i++ {
fmt.Println("Tick at", <-ticker.C)
}
Final Thoughts
The time
package in Go handles most real-world use-cases like:
Scheduling tasks
Measuring time between events
Formatting logs
Sleep and timers
🔖 Quick Cheat Sheet
Task | Code |
Current time | time.Now() |
Add time | t.Add(2 * time.Hour) |
Subtract time | t1.Sub(t2) |
Sleep | time.Sleep(2 * time.Second) |
Parse string | time.Parse(layout, str) |
Format time | t.Format(layout) |
Conclusion
Time handling in Go might look a bit quirky at first—especially the formatting part—but once you get used to it, it’s super clean and predictable. Whether you’re building a scheduler, doing time-based logging, or writing an uptime monitor, the time package gives you all the necessary tools without overcomplicating things. Just keep the reference layout in mind and you’re good to go.
That’s it! Hope this helped clear up how time and duration work in Go. If you’ve got questions or want to see more examples, feel free to ask in the comments. Happy coding! 🧑💻⌛