Time and Text in Go

Format and parse dates with Go's reference time, handle durations, timezones and the monotonic clock, and work with strings, strconv and strings.Builder.

Dates and strings appear in every program. This section covers the time, strings and strconv packages and the mistakes that are easy to make with them.

Formatting and Parsing Time

t.Format("2006-01-02 15:04:05")

Layouts are written with the reference date Mon Jan 2 15:04:05 MST 2006. Parse with time.Parse(layout, value).

Durations, Timezones and Monotonic Time

time.Duration with units, time.LoadLocation and time/tzdata, comparing with Equal, and measuring with time.Since.

strings, strconv and strings.Builder

Splitting and trimming with strings, number conversion with strconv, and fast string building in loops.

Silent mistakes:

A wrong time layout and string(n) both compile and run without errors. They just give the wrong text, so check the output.

Summary

Remember the reference date for layouts, store times in UTC, and use strings, strconv and strings.Builder for text.

Formatting and Parsing Time in Go

Why Go formats dates with 2006-01-02 15:04:05, the layout constants, parsing strings into time.Time, and the common layout mistakes.

Durations, Timezones and Monotonic Time in Go

Work with time.Duration, convert between timezones with time.LoadLocation, compare times correctly, and measure elapsed time with the monotonic clock.

strings, strconv and strings.Builder in Go

Everyday string work in Go with the strings package, convert between strings and numbers with strconv, and build strings efficiently with strings.Builder.