ProgramGuru

The time Package

Start with The time Package

The time package represents instants, durations, time zones and formatting rules.

What you’ll learn

  • Explain the main purpose of the time package.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

time.Date constructs a specific instant with a location. Go formats a time using the reference layout 2006-01-02 15:04:05, not a typical YYYY-MM-DD placeholder format. time.Duration supports arithmetic such as adding 90 * time.Minute.

Use UTC when consistent cross-system timestamps are important, and convert to a user’s location for display. Avoid comparing rendered timestamp strings when you intend to compare instants.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for timeAn instant and a duration play different roles.Fixed UTC instantStep 1Add 90 minutesStep 2Format resultStep 3Compute durationStep 4An instant and a duration play different roles.
An instant and a duration play different roles.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"time"
)

func main() {
	start := time.Date(2026, time.October, 11, 9, 0, 0, 0, time.UTC)
	end := start.Add(90 * time.Minute)
	fmt.Println("Start:", start.Format("2006-01-02 15:04"))
	fmt.Println("End:", end.Format("15:04"))
	fmt.Println("Minutes:", end.Sub(start).Minutes())
}

Output

Start: 2026-10-11 09:00
End: 10:30
Minutes: 90

Trace what the program does

The date is constructed explicitly, so it does not depend on the current clock. Adding 90 minutes advances 09:00 to 10:30, and Sub reports a duration of 90 minutes.

Avoid common mistakes

  • Go layout symbols are based on the reference time, not YYYY/MM/DD format tokens.
  • Avoid confusing wall-clock formatting with the actual instant or duration.

Try it yourself

Add 48 hours to the fixed date and print the result as 2006-01-02.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which layout prints a four-digit year, month and day?
Choose one answer. You can try again.

Answer and explanation

2006-01-02

Correct. The date is constructed explicitly, so it does not depend on the current clock.

What you should remember

You have practiced The time Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The os Package →