Record wall-clock time for an event
#time.Now supplies a time value; format UTC explicitly when your interchange format requires it.
Fragment
Import time. time.Time can also carry a monotonic component for supported in-process elapsed comparisons.
Reference
Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.
TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.
time.Now supplies a time value; format UTC explicitly when your interchange format requires it.
Fragment
Import time. time.Time can also carry a monotonic component for supported in-process elapsed comparisons.
time.Since uses the monotonic reading carried by a compatible time.Now value when available.
Fragment
Import time; elapsed is a time.Duration.
rand/v2 supplies general-purpose pseudorandom generation. IntN returns a value in [0,n).
Fragment
Go 1.22+. Import math/rand/v2. It is not crypto/rand.
time.Duration is an int64 count of nanoseconds with typed constants (time.Second, time.Millisecond), so 30 * time.Second reads naturally and prints as 30s. A variable integer has to be converted first: time.Duration(n) * time.Second. Hours and Seconds return float64; Milliseconds returns int64; ParseDuration reads "1h15m30s"; Round and Truncate change precision. Time.Add and Time.Sub move between instants and durations.
Complete program
Complete program.
In practice: take time.Duration in APIs instead of an int with a unit in its name, parse config with time.ParseDuration, and use AddDate for calendar steps such as "one month later".
time.Duration(5) is 5 nanoseconds. time.Sleep(5) is the classic mistake; go vet does not catch it.
Durations overflow at about 292 years; Sub between distant times saturates to the minimum or maximum Duration.
ParseDuration has no unit for days ("d"); use hours.
Go formats and parses with a layout written as the reference time Mon Jan 2 15:04:05 MST 2006 (1 2 3 4 5 6 -0700), instead of %Y-style codes. time.RFC3339, time.DateOnly and time.DateTime are predefined layouts. time.Parse returns an error for invalid input, keeps the parsed offset, and treats a layout with no zone as UTC; time.ParseInLocation names the zone instead.
Complete program
Complete program.
In practice: use time.RFC3339 (or RFC3339Nano) for interchange, compare parsed times with Equal rather than ==, and write custom layouts by copying the reference date. go vet catches the common mistake of swapped month and day digits.
Use t.Equal(u), not t == u: == also compares the location and the monotonic reading.
time.Parse with an abbreviation like EST does not know its offset unless it matches the local zone; it fabricates a zero-offset location with that name.
Parse range-checks fields (an hour of 24 or 30 February is an error), but the RFC3339 layout still accepts some inputs the RFC does not, such as an offset of +24:00.
time.LoadLocation("America/New_York") loads an IANA zone, t.In(loc) shows the same instant in that zone, and time.Date(..., loc) builds a wall time there with the right offset for that day. Zone data comes from the OS (/usr/share/zoneinfo), $ZONEINFO, or the time/tzdata package embedded in the binary. time.UTC and time.Local are predefined; Local comes from TZ or the OS.
Complete program
Complete program. Embeds time/tzdata, so it runs on hosts without zone files.
In practice: keep times in UTC internally, load each Location once at startup, and import _ "time/tzdata" in programs that run in minimal containers without zoneinfo. For "same time tomorrow", use t.AddDate(0, 0, 1), which steps the wall clock in t's location; t.Add(24 * time.Hour) is exact time and lands an hour off across a DST change. Wall times in a DST gap or overlap are ambiguous; time.Date picks an offset and does not report it.
time/tzdata adds about 450 KB; alternatively build with -tags timetzdata.
In does not change the instant: winter.In(loc).Equal(winter) is true.
time.FixedZone("X", -5*3600) is a fixed offset with no DST, useful only for parsed offsets.
math/rand/v2 (Go 1.22+) separates sources from the Rand methods. The top-level functions (rand.IntN, rand.Shuffle) use a randomly seeded generator that cannot be reseeded. For a reproducible sequence, own one: rand.New(rand.NewPCG(seed1, seed2)) (or rand.NewChaCha8(seed)), then call IntN, Float64, Perm, Shuffle and NormFloat64 on it.
Complete program
Complete program (Go 1.22+).
In practice: pass a *rand.Rand into code that needs randomness, seed it from a flag or test parameter, and log the seed. PCG is the fast default for simulations; ChaCha8 is also seedable and is cryptographically strong.
The old math/rand package's rand.Seed is deprecated (a no-op since Go 1.24 unless GODEBUG randseednop=0); use v2 with an explicit source.
A *rand.Rand is not safe for concurrent use; give each goroutine its own, seeded from the parent.
Shuffle and Perm consume values from the generator, so adding a call earlier in a test changes everything drawn after it; use one generator per independent stream.
crypto/rand reads the OS generator. rand.Text (Go 1.24+) returns a 26-character base32 string with at least 128 bits of randomness, ready to use as a token; rand.Read fills a byte slice; rand.Int returns an unbiased big.Int below a bound. Since Go 1.24, Read never returns an error: if the OS source fails, the program crashes rather than continue with weak randomness.
Complete program
Complete program (Go 1.24+ for rand.Text).
In practice: use rand.Text for tokens and IDs, rand.Read plus base64.RawURLEncoding for raw keys, and crypto/subtle.ConstantTimeCompare to check secrets. Do not use math/rand for anything security-related.
Before Go 1.24, check the error from rand.Read; code that ignores it is still common in older projects.
math/rand/v2 ChaCha8 is cryptographically strong but seedable; for secrets prefer crypto/rand, which is never seeded by you.
ConstantTimeCompare returns 0 immediately for different lengths, which leaks only the length.