The time Package
Getting the Current Time
time.Now() returns a time.Time value representing the current moment, which carries a full date, time, and time zone, and supports formatting and arithmetic.
Example: Getting the Current Time
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("current year:", now.Year())
}
Login to try C/C++/Java/PHP code in the editor
Measuring Elapsed Time
time.Since(start) returns a time.Duration representing how long has passed since a recorded start time -- the standard way to time how long an operation takes.
Example: Measuring Elapsed Time
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
sum := 0
for i := 0; i < 1000000; i++ {
sum += i
}
elapsed := time.Since(start)
fmt.Println("sum:", sum, "took at least 0ns:", elapsed >= 0)
}
Login to try C/C++/Java/PHP code in the editor
Working with Durations
A time.Duration represents a span of time and is usually constructed with constants like time.Second or time.Millisecond, which makes duration-based code, like sleeps and timeouts, self-documenting.
Note: Always build durations from the named constants (time.Second, etc.) instead of raw integers, for clarity.
Example: Working with Durations
package main
import (
"fmt"
"time"
)
func main() {
d := 2 * time.Second
fmt.Println("duration:", d)
time.Sleep(1 * time.Millisecond)
fmt.Println("slept briefly")
}
Login to try C/C++/Java/PHP code in the editor
- Comparing two time.Time values with == when Sub/Before/After/Equal are more correct due to internal monotonic clock readings.
- Forgetting time.Sleep pauses the whole goroutine, blocking everything else it might be doing.
- Confusing a time.Duration's numeric value (nanoseconds) with a human unit, instead of using constants like time.Second for clarity.
- time.Now returns the current local time as a time.Time value.
- time.Duration represents a length of time, expressed with constants like time.Second or time.Millisecond.
- time.Since computes how much time has elapsed since a given time.Time.
- time.Sleep pauses the current goroutine for a given duration.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: