⏰ The Time Package: Your Go Clock Friend
What is Time in Go?
Imagine you have a magical watch on your wrist. This watch doesn’t just tell you what time it is right now—it can also:
- Remember any moment from the past
- Schedule things for the future
- Tell you exactly how long something took
In Go, the time package is your magical watch! 🪄
🎯 The Big Picture
graph TD A["Time Package"] --> B["Time Operations"] A --> C["Time-based Events"] A --> D["Formatting & Parsing"] B --> B1["Get Current Time"] B --> B2["Add/Subtract Time"] B --> B3["Compare Times"] C --> C1["Timers"] C --> C2["Tickers"] C --> C3["Sleeping"] D --> D1["Time to Text"] D --> D2["Text to Time"]
Part 1: Time Operations
Getting the Current Time
Think of this like asking your watch: “What time is it RIGHT NOW?”
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("Current time:", now)
}
Output: Current time: 2024-01-15 10:30:45.123456789 +0000 UTC
Breaking Down a Time
Your magical watch can tell you each piece separately:
now := time.Now()
year := now.Year() // 2024
month := now.Month() // January
day := now.Day() // 15
hour := now.Hour() // 10
minute := now.Minute() // 30
second := now.Second() // 45
Simple Example:
fmt.Printf("Today is %s %d, %d\n",
now.Month(), now.Day(), now.Year())
// Output: Today is January 15, 2024
Creating Specific Times
What if you want to remember your birthday? You can create any moment in time:
// Create a specific date and time
birthday := time.Date(
2024, // Year
time.March, // Month
15, // Day
14, // Hour (2 PM)
30, // Minute
0, // Second
0, // Nanosecond
time.UTC, // Timezone
)
fmt.Println("Birthday:", birthday)
Adding and Subtracting Time
Adding Time with Add()
“What time will it be in 2 hours?”
now := time.Now()
// Add 2 hours
later := now.Add(2 * time.Hour)
// Add 30 minutes
halfHourLater := now.Add(30 * time.Minute)
// Add 1 day (24 hours)
tomorrow := now.Add(24 * time.Hour)
The Duration Friends
Go has built-in time units you can use:
| Unit | How to Write It |
|---|---|
| 1 nanosecond | time.Nanosecond |
| 1 microsecond | time.Microsecond |
| 1 millisecond | time.Millisecond |
| 1 second | time.Second |
| 1 minute | time.Minute |
| 1 hour | time.Hour |
Mix and Match:
// 2 hours + 30 minutes + 45 seconds
duration := 2*time.Hour +
30*time.Minute +
45*time.Second
Subtracting Time
Just use negative numbers!
now := time.Now()
// 3 hours ago
threeHoursAgo := now.Add(-3 * time.Hour)
// Yesterday
yesterday := now.Add(-24 * time.Hour)
Adding Years, Months, Days with AddDate()
For calendar math (years, months, days), use AddDate():
now := time.Now()
// Add 1 year, 2 months, 3 days
future := now.AddDate(1, 2, 3)
// Go back 1 year
lastYear := now.AddDate(-1, 0, 0)
Comparing Times
Is Time A Before Time B?
birthday := time.Date(2024, 3, 15, 0, 0, 0, 0, time.UTC)
now := time.Now()
if now.Before(birthday) {
fmt.Println("Birthday hasn't happened yet!")
}
if now.After(birthday) {
fmt.Println("Birthday already passed!")
}
if now.Equal(birthday) {
fmt.Println("It's your birthday!")
}
Finding the Difference Between Times
“How long until my birthday?”
birthday := time.Date(2024, 12, 25, 0, 0, 0, 0, time.UTC)
now := time.Now()
// Sub returns a Duration
timeUntil := birthday.Sub(now)
fmt.Printf("%.0f hours until birthday!\n",
timeUntil.Hours())
Duration Methods:
d := 90 * time.Minute
d.Hours() // 1.5
d.Minutes() // 90
d.Seconds() // 5400
d.Milliseconds() // 5400000
Part 2: Time-based Events
Sleeping (Pausing Your Program)
Sometimes your program needs to take a nap! 😴
fmt.Println("Going to sleep...")
time.Sleep(2 * time.Second)
fmt.Println("I'm awake!")
This pauses your program for exactly 2 seconds.
Timers: One-Time Alarms
A Timer is like setting an alarm that rings once.
Basic Timer
// Create a timer for 3 seconds
timer := time.NewTimer(3 * time.Second)
fmt.Println("Timer started!")
// Wait for timer to finish
<-timer.C // C is a channel
fmt.Println("Timer finished!")
Stopping a Timer Early
timer := time.NewTimer(10 * time.Second)
// Changed my mind! Stop it!
stopped := timer.Stop()
if stopped {
fmt.Println("Timer was stopped")
}
Quick One-Shot with After()
If you just want to wait once:
fmt.Println("Waiting...")
<-time.After(2 * time.Second)
fmt.Println("Done waiting!")
Using AfterFunc (Do Something After Time)
// Run a function after 2 seconds
time.AfterFunc(2*time.Second, func() {
fmt.Println("This runs after 2 seconds!")
})
// Keep program running
time.Sleep(3 * time.Second)
Tickers: Repeating Alarms
A Ticker is like an alarm that rings every X seconds, forever!
// Tick every 1 second
ticker := time.NewTicker(1 * time.Second)
count := 0
for tick := range ticker.C {
count++
fmt.Println("Tick!", tick)
if count >= 5 {
ticker.Stop()
break
}
}
fmt.Println("Ticker stopped!")
Quick Ticks with Tick()
For simple cases (note: can’t be stopped!):
for tick := range time.Tick(500 * time.Millisecond) {
fmt.Println("Tick at", tick)
}
⚠️ Warning: time.Tick() leaks memory if you don’t run it forever. Use NewTicker() when you need to stop it!
Timeouts with Select
Combine timers with channels for timeouts:
select {
case result := <-someChannel:
fmt.Println("Got result:", result)
case <-time.After(5 * time.Second):
fmt.Println("Timeout! Took too long.")
}
Part 3: Time Formatting and Parsing
The Magic Reference Time
Go uses a special moment for formatting:
Mon Jan 2 15:04:05 MST 2006
This is January 2, 2006, at 3:04:05 PM
Why these numbers? They’re 1, 2, 3, 4, 5, 6, 7!
- Month: 01 (January)
- Day: 02
- Hour: 03 (or 15 for 24h)
- Minute: 04
- Second: 05
- Year: 06 (2006)
- Timezone: -07:00
Formatting Time (Time → Text)
Basic Formatting
now := time.Now()
// Custom format
fmt.Println(now.Format("2006-01-02"))
// Output: 2024-01-15
fmt.Println(now.Format("January 2, 2006"))
// Output: January 15, 2024
fmt.Println(now.Format("3:04 PM"))
// Output: 10:30 AM
fmt.Println(now.Format("15:04:05"))
// Output: 10:30:45
Common Format Patterns
| Pattern | Example Output |
|---|---|
2006-01-02 |
2024-01-15 |
02/01/2006 |
15/01/2024 |
Jan 2, 2006 |
Jan 15, 2024 |
Monday |
Monday |
Mon |
Mon |
3:04 PM |
10:30 AM |
15:04 |
10:30 |
Built-in Format Constants
Go provides ready-made formats:
now := time.Now()
now.Format(time.RFC3339)
// 2024-01-15T10:30:45Z
now.Format(time.Kitchen)
// 10:30AM
now.Format(time.DateOnly)
// 2024-01-15
now.Format(time.TimeOnly)
// 10:30:45
Parsing Time (Text → Time)
Basic Parsing
// Parse a date string
dateStr := "2024-03-15"
t, err := time.Parse("2006-01-02", dateStr)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Parsed:", t)
More Parsing Examples
// Parse different formats
t1, _ := time.Parse(
"January 2, 2006",
"March 15, 2024")
t2, _ := time.Parse(
"02/01/2006",
"15/03/2024")
t3, _ := time.Parse(
"2006-01-02 15:04",
"2024-03-15 14:30")
Parsing with Timezone
// Parse with timezone
loc, _ := time.LoadLocation("America/New_York")
t, _ := time.ParseInLocation(
"2006-01-02 15:04",
"2024-03-15 14:30",
loc,
)
Working with Timezones
Get Local Time
now := time.Now() // Already in local timezone
fmt.Println(now)
Convert to UTC
now := time.Now()
utc := now.UTC()
fmt.Println("UTC:", utc)
Convert to Another Timezone
now := time.Now()
// Load timezone
tokyo, _ := time.LoadLocation("Asia/Tokyo")
nyc, _ := time.LoadLocation("America/New_York")
// Convert
tokyoTime := now.In(tokyo)
nycTime := now.In(nyc)
fmt.Println("Tokyo:", tokyoTime)
fmt.Println("NYC:", nycTime)
🎯 Quick Reference
graph LR A["Time Operations"] --> A1["time.Now#40;#41;"] A --> A2["time.Date#40;...#41;"] A --> A3["t.Add#40;duration#41;"] A --> A4["t.AddDate#40;y,m,d#41;"] A --> A5["t.Sub#40;other#41;"] A --> A6["t.Before/After/Equal"] B["Time Events"] --> B1["time.Sleep#40;d#41;"] B --> B2["time.NewTimer#40;d#41;"] B --> B3["time.NewTicker#40;d#41;"] B --> B4["time.After#40;d#41;"] B --> B5["time.AfterFunc#40;d,fn#41;"] C["Format/Parse"] --> C1["t.Format#40;layout#41;"] C --> C2["time.Parse#40;layout,s#41;"] C --> C3["t.UTC#40;#41; / t.Local#40;#41;"] C --> C4["t.In#40;location#41;"]
🌟 Real-World Example
Here’s a complete example that uses everything:
package main
import (
"fmt"
"time"
)
func main() {
// Get current time
now := time.Now()
fmt.Println("Now:",
now.Format("Jan 2, 2006 3:04 PM"))
// When does the sale end?
saleEnd := time.Date(
2024, 12, 31, 23, 59, 59, 0,
time.Local)
// How much time left?
timeLeft := saleEnd.Sub(now)
fmt.Printf("Sale ends in %.0f days!\n",
timeLeft.Hours()/24)
// Countdown ticker
ticker := time.NewTicker(1 * time.Second)
count := 3
for range ticker.C {
fmt.Println(count, "...")
count--
if count == 0 {
ticker.Stop()
fmt.Println("GO! 🚀")
break
}
}
}
🎉 You Did It!
You now know how to:
- ✅ Get and create times
- ✅ Add and subtract durations
- ✅ Compare times
- ✅ Use timers and tickers
- ✅ Format times into text
- ✅ Parse text into times
- ✅ Work with timezones
The time package is your friend for anything involving time in Go! 🕐
