Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Working with Time in Go Without the Headaches

1 min read .
Working with Time in Go Without the Headaches

Time handling looks simple until time zones, parsing, durations, and scheduling enter the picture. Go’s standard time package covers the common cases without requiring third-party libraries.

Current Time

currentTime := time.Now()
fmt.Println("Now:", currentTime)

time.Now() returns the current local time according to the process environment.

Format and Parse

Go uses a reference-time layout instead of symbols such as YYYY or MM. The reference is:

Mon Jan 2 15:04:05 MST 2006

For example:

formatted := currentTime.Format("2006-01-02 15:04:05")
fmt.Println("Formatted:", formatted)

parsed, err := time.Parse("2006-01-02 15:04:05", "2024-08-24 13:45:00")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Parsed:", parsed)

time.Parse interprets a layout without a zone as UTC. If the input represents time in a specific location, use time.ParseInLocation.

Add Durations and Calculate Differences

future := currentTime.Add(2 * time.Hour)
past := currentTime.Add(-30 * time.Minute)

fmt.Println("Two hours from now:", future)
fmt.Println("Thirty minutes ago:", past)
fmt.Println("Difference:", future.Sub(currentTime))

time.Duration is useful for elapsed time such as seconds, minutes, and hours. Calendar operations involving months or years should normally use AddDate instead because calendar units do not have fixed durations.

nextMonth := currentTime.AddDate(0, 1, 0)

Work with Time Zones

loc, err := time.LoadLocation("Asia/Jakarta")
if err != nil {
    log.Fatal(err)
}

fmt.Println("Jakarta time:", currentTime.In(loc))

On systems without time-zone data, LoadLocation can fail. Go applications running in minimal containers may need the time/tzdata package embedded in the binary.

Periodic Work with a Ticker

ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()

for i := 0; i < 5; i++ {
    t := <-ticker.C
    fmt.Println("Tick:", t)
}

For server applications, combine tickers with a context.Context so background work can stop during shutdown.

Conclusion

The time package covers current timestamps, formatting, parsing, durations, time zones, and simple periodic scheduling. The main pitfalls are usually semantic rather than syntactic: know which time zone an input belongs to, distinguish elapsed durations from calendar arithmetic, and always handle parsing or location-loading errors.

Related Posts

chevron-up