Construct fixed time values and durations
Construct fixed time values and durations
A time.Time identifies an instant; a time.Duration measures a span as an integer number of nanoseconds. Use time.Date with explicit calendar fields and a location for repeatable examples. Multiplying a number by time.Minute or time.Second states its unit explicitly. The Gregorian calendar is used without leap seconds.
package main
import ( "fmt" "time")
func main() { start := time.Date(2026, time.January, 15, 9, 0, 0, 0, time.UTC) end := start.Add(90 * time.Minute) fmt.Println(start.Format(time.RFC3339)) fmt.Println(end.Format(time.RFC3339)) fmt.Println(end.Sub(start))}Date takes year, month, day, hour, minute, second, nanosecond and location. Add returns a new value, leaving start unchanged; Sub returns a Duration. Date normalizes out-of-range fields, so it is not a strict input validator. The zero Time is year 1 in UTC; use IsZero to detect it.
Expected output:
2026-01-15T09:00:00Z2026-01-15T10:30:00Z1h30m0sParse a duration with units
package main
import ( "fmt" "time")
func check(e error) { if e != nil { panic(e) }}
func main() { d, e := time.ParseDuration("2h15m") check(e) fmt.Println(d.Minutes()) _, e = time.ParseDuration("15") fmt.Println(e != nil)}ParseDuration understands signed spans with units such as h, m, s, ms, us and ns. It does not parse days or months. Duration(15) means 15 nanoseconds, not seconds. Check parsing errors and validate bounds before multiplying untrusted numbers: Duration is a signed 64-bit integer and can overflow.
Expected output:
135trueTry it locally
Parse 45m30s and print its number of seconds.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Time and scheduling 01: Construct fixed time values and durations
Check the lesson objective before moving on.
What does time.Duration(10) represent?
What does end.Sub(start) return?