Master Go's time Package: From Basics to Advanced Usage
This article introduces Go's time package, explaining its core types such as Month, Weekday, Duration, Location, and Time, and demonstrates how to work with timers, tickers, and time parsing through clear examples and code snippets.
Overview: The Go time package provides functions for displaying and measuring time using the Gregorian calendar. It defines key types like Month, Weekday, Duration, Location, and Time, each with constants and methods.
Month
Monthis an int where 1‑12 represent the calendar months.
// A Month specifies a month of the year (January = 1, ...).
type Month int
const (
January Month = 1 + iota
February
March
April
May
June
July
August
September
October
November
December
)
// String returns the English name of the month.
func (m Month) String() string {
if January <= m && m <= December {
return longMonthNames[m-1]
}
buf := make([]byte, 20)
n := fmtInt(buf, uint64(m))
return "%!Month(" + string(buf[n:]) + ")"
}Weekday
Weekdayis an int where 0‑6 represent Sunday through Saturday.
// A Weekday specifies a day of the week (Sunday = 0, ...).
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
// String returns the English name of the day.
func (d Weekday) String() string {
if Sunday <= d && d <= Saturday {
return longDayNames[d]
}
buf := make([]byte, 20)
n := fmtInt(buf, uint64(d))
return "%!Weekday(" + string(buf[n:]) + ")"
}Duration
Durationrepresents a time interval as an int64 nanosecond count.
// A Duration represents the elapsed time between two instants as an int64 nanosecond count.
type Duration int64
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)Common usage example:
func main() {
d := 1*time.Hour + 2*time.Minute + 3*time.Second + 4567
fmt.Println(d.String())
fmt.Println(d.Hours())
fmt.Println(d.Minutes())
fmt.Println(d.Seconds())
fmt.Println(d.Milliseconds())
fmt.Println(d.Microseconds())
fmt.Println(d.Nanoseconds())
}Location
Different regions use different time zones. Go represents a time zone with Location. Two built‑in locations are Local (the system's local zone) and UTC (Coordinated Universal Time).
// Example of loading a location based on the TZ environment variable.
func initLocal() {
tz, ok := syscall.Getenv("TZ")
switch {
case !ok:
z, err := loadLocation("localtime", []string{"/etc"})
if err == nil {
localLoc = *z
localLoc.name = "Local"
return
}
case tz != "" && tz != "UTC":
if z, err := loadLocation(tz, zoneSources); err == nil {
localLoc = *z
return
}
}
// Fallback to UTC.
localLoc.name = "UTC"
}Time
The Time type represents an instant with nanosecond precision. It should be stored by value, not by pointer, and can be compared with Before, After, and Equal. Methods such as Sub, Add, and Unix manipulate time values.
type Time struct {
wall uint64 // wall time seconds and nanoseconds
ext int64 // optional monotonic clock reading
loc *Location
}Timer and Ticker
A Timer fires once at a specified time, while a Ticker fires repeatedly at a fixed interval.
// Timer example
timer := time.NewTimer(3 * time.Second)
<-timer.C // blocks until the timer fires
// Ticker example
ticker := time.NewTicker(3 * time.Second)
for t := range ticker.C {
fmt.Println("tick at", t)
}Key Points
Use time.Time values (not pointers) to store timestamps.
Format strings use the reference layout "2006-01-02 15:04:05".
Zero time is January 1, year 1, 00:00:00 UTC.
Wall clocks count seconds since Jan 1 1885; monotonic clocks count since process start.
Create Timer instances with NewTimer or AfterFunc. Timer triggers once; Ticker triggers repeatedly. time.Parse defaults to UTC; use ParseInLocation for local zones.
TiPaiPai Technical Team
At TiPaiPai, we focus on building engineering teams and culture, cultivating technical insights and practice, and fostering sharing, growth, and connection.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
