0Pricing
Go Academy · Lesson

time Package Essentials

Working with time, durations, and formatting

time Package Essentials is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

time.Time — The Core Type

The time package's central type is time.Time. Get the current time with time.Now():

package main
import ("fmt"; "time")

func main() {
    now := time.Now()
    fmt.Println(now)              // 2024-01-15 10:30:00.123456789 +0000 UTC
    fmt.Println(now.Year())       // 2024
    fmt.Println(now.Month())      // January
    fmt.Println(now.Day())        // 15
    fmt.Println(now.Hour())       // 10
    fmt.Println(now.Minute())     // 30
    fmt.Println(now.Weekday())    // Monday
}

time.Duration

time.Duration represents elapsed time in nanoseconds. Use typed constants for readability:

package main
import ("fmt"; "time")

func main() {
    d := 2*time.Hour + 30*time.Minute + 15*time.Second
    fmt.Println(d)              // 2h30m15s
    fmt.Println(d.Hours())      // 2.504166...
    fmt.Println(d.Minutes())    // 150.25
    fmt.Println(d.Seconds())    // 9015
    fmt.Println(d.Milliseconds()) // 9015000
}

time.Add and time.Sub

Add a duration to a time, or subtract two times to get a duration:

package main
import ("fmt"; "time")

func main() {
    now := time.Now()

    tomorrow := now.Add(24 * time.Hour)
    fmt.Println(tomorrow.Format("2006-01-02"))

    deadline := now.Add(30 * time.Minute)
    remaining := time.Until(deadline)  // alias for deadline.Sub(now)
    fmt.Printf("%.0f minutes left\n", remaining.Minutes())
}

Formatting and Parsing Times

Go uses a reference time Mon Jan 2 15:04:05 MST 2006 as the format template (the values 1-7 in order):

package main
import ("fmt"; "time")

func main() {
    now := time.Now()

    // Format
    fmt.Println(now.Format("2006-01-02"))          // 2024-01-15
    fmt.Println(now.Format("02/01/2006 15:04:05")) // 15/01/2024 10:30:00
    fmt.Println(now.Format(time.RFC3339))          // 2024-01-15T10:30:00Z
    fmt.Println(now.Format(time.Kitchen))          // 10:30AM
}

time.Parse — Parsing Strings

Parse a string into a time.Time using the same reference template:

package main
import ("fmt"; "time")

func main() {
    s := "2024-01-15"
    t, err := time.Parse("2006-01-02", s)
    if err != nil {
        fmt.Println("parse error:", err)
        return
    }
    fmt.Println(t.Year(), t.Month(), t.Day()) // 2024 January 15

    // Parse RFC3339 (ISO 8601):
    t2, _ := time.Parse(time.RFC3339, "2024-01-15T10:30:00Z")
    fmt.Println(t2)
}

time.Sleep and Timers

Pause execution with time.Sleep; create one-shot timers with time.NewTimer:

package main
import ("fmt"; "time")

func main() {
    start := time.Now()
    time.Sleep(100 * time.Millisecond)
    fmt.Printf("slept for %v\n", time.Since(start))

    // One-shot timer
    timer := time.NewTimer(200 * time.Millisecond)
    <-timer.C  // blocks until timer fires
    fmt.Println("timer fired")
}

time.Ticker for Repeated Events

time.NewTicker sends on its channel at regular intervals:

package main
import ("fmt"; "time")

func main() {
    ticker := time.NewTicker(500 * time.Millisecond)
    defer ticker.Stop()  // always stop to avoid goroutine leak

    for i := 0; i < 3; i++ {
        t := <-ticker.C
        fmt.Println("tick at", t.Format("15:04:05.000"))
    }
}

time.Since and time.Until

Convenient shortcuts for measuring elapsed time and time until an event:

package main
import ("fmt"; "time")

func benchmark(fn func()) time.Duration {
    start := time.Now()
    fn()
    return time.Since(start)  // = time.Now().Sub(start)
}

func main() {
    d := benchmark(func() { time.Sleep(50 * time.Millisecond) })
    fmt.Printf("took %v\n", d)

    deadline := time.Now().Add(5 * time.Minute)
    fmt.Printf("%.0f minutes remaining\n", time.Until(deadline).Minutes())
}

Time Zones

Go handles time zones with time.Location. Load zones with time.LoadLocation:

package main
import ("fmt"; "time")

func main() {
    utc := time.Now().UTC()
    fmt.Println(utc)

    loc, err := time.LoadLocation("America/New_York")
    if err != nil { panic(err) }
    nyTime := utc.In(loc)
    fmt.Println(nyTime)

    // Compare times — always in UTC internally
    fmt.Println(utc.Equal(nyTime)) // true — same instant
}

time.Unix — Unix Timestamps

Convert between time.Time and Unix timestamps:

package main
import ("fmt"; "time")

func main() {
    now := time.Now()
    unix := now.Unix()            // seconds since epoch
    unixMilli := now.UnixMilli()  // milliseconds
    unixNano := now.UnixNano()    // nanoseconds

    fmt.Println(unix, unixMilli, unixNano)

    // Convert back:
    t := time.Unix(unix, 0)
    fmt.Println(t.Format(time.RFC3339))
}

Quick Check

What reference time does Go use as its format template?

Recap: time Package

Summary:

  • time.Now() — current time; fields via .Year(), .Month(), etc.
  • time.Duration — nanoseconds; use time.Hour, time.Minute, etc.
  • t.Format(layout) / time.Parse(layout, s) — format uses reference time 2006-01-02 15:04:05
  • time.Since / time.Until for elapsed/remaining time
  • time.NewTicker for periodic events — always defer Stop()

Frequently asked questions

Is the “time Package Essentials” lesson free?

Yes — the full text of “time Package Essentials” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “time Package Essentials”?

Working with time, durations, and formatting You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “time Package Essentials” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. fmt and strings Packages
  2. strconv, math and sort
  3. time Package Essentials
  4. os and filepath Packages
← Back to Go Academy