0PricingLogin
Go Academy · Lesson

time Package Essentials

Working with time, durations, and formatting

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
}

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