Time
time.Time, time.Now, Duration arithmetic, time.Since and time.Until, Add and Sub, and comparisons with Before, After, and Equal.
The time package provides types and functions for measuring and displaying time. time.Time represents an instant in time with nanosecond precision. time.Duration represents an elapsed duration as an int64 nanosecond count.
time.Now() returns the current local time. Access individual components with methods like Year(), Month(), Day(), Hour(), Minute(), Second(), and Weekday().
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println(now)
fmt.Println(now.Year(), now.Month(), now.Day())
fmt.Println(now.Hour(), now.Minute(), now.Second())
fmt.Println(now.Weekday())
fmt.Println(now.Unix()) // seconds since epoch
fmt.Println(now.UnixNano()) // nanoseconds since epoch
}Build time.Duration values using named constants: time.Second, time.Minute, time.Hour, etc. Add or subtract a duration from a time.Time with Add. Subtract two time.Time values with Sub to get a Duration.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
// Add durations to a time
inAnHour := now.Add(1 * time.Hour)
fmt.Println(inAnHour)
yesterday := now.Add(-24 * time.Hour)
fmt.Println(yesterday)
// Subtract two times to get a duration
diff := now.Sub(yesterday)
fmt.Println(diff) // 24h0m0s
fmt.Println(diff.Hours()) // 24
fmt.Println(diff.Minutes()) // 1440
fmt.Println(diff.Seconds()) // 86400
}time.Since(t) returns the elapsed time since t. time.Until(t) returns the duration until t. Both use the monotonic clock for accuracy. Compare two time.Time values with Before, After, and Equal.
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
time.Sleep(2 * time.Millisecond) // simulate work
elapsed := time.Since(start)
fmt.Printf("elapsed: %v\n", elapsed)
deadline := time.Now().Add(5 * time.Second)
fmt.Printf("time until deadline: %v\n", time.Until(deadline))
t1 := time.Now()
t2 := t1.Add(time.Second)
fmt.Println(t1.Before(t2)) // true
fmt.Println(t1.After(t2)) // false
fmt.Println(t1.Equal(t1)) // true
}In production
time.Time contains both a wall clock reading and a monotonic clock reading. time.Since uses the monotonic clock, which is immune to NTP adjustments and DST transitions - always prefer it for measuring elapsed time. Use the wall clock (from time.Now()) for timestamps you store in databases or logs. Never compare two time.Time values with == when one may have been deserialized from a database: the monotonic component is stripped on round-trips through time.Time.MarshalJSON or SQL drivers, making the Equal method (which compares only wall time) the correct comparison. In HTTP handlers, record time.Now() at the top of the handler to measure end-to-end latency rather than calling time.Since with a captured start from middleware, where middleware overhead inflates the measurement.
Enjoyed this? Get more essays on software craft delivered to your inbox.
Subscribe free