← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 4 of 10

The time Package

The time package lets Go read the clock, measure how long things take, and work with dates the same way no matter where in the world your program runs.

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

markup
package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	fmt.Println("current year:", now.Year())
}

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

markup
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)
}

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

markup
package main

import (
	"fmt"
	"time"
)

func main() {
	d := 2 * time.Second
	fmt.Println("duration:", d)
	time.Sleep(1 * time.Millisecond)
	fmt.Println("slept briefly")
}
Common Mistakes
  1. Comparing two time.Time values with == when Sub/Before/After/Equal are more correct due to internal monotonic clock readings.
  2. Forgetting time.Sleep pauses the whole goroutine, blocking everything else it might be doing.
  3. Confusing a time.Duration's numeric value (nanoseconds) with a human unit, instead of using constants like time.Second for clarity.
Chapter Summary
  • 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.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.