Skip to content

time.Time, Formatting/Parsing, Time Zones, Timers, math/rand & Number Parsing ​

"The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time." — Go standard library documentation, package time, section "Monotonic Clocks"

Summary: A time.Time is an instant with two clock readings and a location, a Duration is a count of nanoseconds, layouts are written with one magic reference date, time zones come from the IANA database, timers changed their semantics in Go 1.23, random numbers have a seedable fast family and a secure family, and numbers must be parsed with explicit base and bit size and money kept in integers. Focus: wall and monotonic readings, Sub/Since/Until, Equal versus ==, IsZero, Duration arithmetic, layouts and the parsing time ... cannot parse errors, LoadLocation and time/tzdata, UTC storage, DST traps and the Asia/Tehran tzdata history, Timer/Ticker/time.After/AfterFunc, sleeping with contexts, measuring time, fake clocks, scheduling, persistence (PostgreSQL timestamptz, Unix epoch, JSON), Jalali dates, math/rand, math/rand/v2, crypto/rand, strconv, math/big, minor units and number formatting. Learning goal: Store and compare instants without ever being off by a zone, an hour or a stale tick, pick the right random source for a task in one question, and turn text into numbers (and money) without silent surprises.

This page owns the time package, the random-number packages and number parsing/formatting. It does not re-teach neighbours: select and timeouts on channels are in select: Multiplexing, Non-Blocking Ops, Timeouts, for-select, cancellation and deadlines propagated across calls are in context: Cancellation, Deadlines, Values, the channel and goroutine mechanics under timers are in Goroutines & Channels, hashing and password primitives that use crypto/rand are in Hashing & Crypto, JSON struct tags are in JSON, XML, Struct Tags, Encoder/Decoder, Base64, table-driven tests and benchmarks are in Testing & Benchmarking, and token-bucket limiters built on time are in Rate Limiting in Go. Here each of them gets a paragraph and a link.

Facts below come from the package documentation as printed by go doc for Go 1.27.4 (the toolchain on the machine that wrote this page), the Go 1.20, 1.22, 1.23, 1.24 and 1.25 release notes, the Go blog posts "Evolving the Go Standard Library with math/rand/v2" and "Secure Randomness in Go 1.22", the IANA tz database NEWS file and the PostgreSQL manual (current). pkg.go.dev refuses scripted downloads (HTTP 403 to curl), so package text was read from go doc and go.dev/src instead. Snippets live in one module with go 1.24 in go.mod; they pass gofmt, go vet and go test -race.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why time is harder than it looksWhy it exists
Where the rules come fromWhere it comes from
Wall clock versus monotonic clock, Since, Subtime.Time
== versus Equal, the zero time, IsZeroComparing and the zero time
time.Duration, ParseDuration, 5 * time.SecondDuration
2006-01-02T15:04:05Z07:00 and the reference dateLayouts: Format and Parse
parsing time ... cannot parse ... as ...Parse errors
LoadLocation, Local, FixedZone, time/tzdataTime zones
Store UTC, show localThe UTC storage rule
23-hour and 25-hour days, gaps, overlapsDST traps
Asia/Tehran, Iran stopped DST in 2022tzdata updates and Iran
NewTimer, Stop, Reset, Go 1.23 changesTimer and Ticker
time.After in a loop, AfterFunctime.After and AfterFunc
time.Sleep and cancelling itSleeping and contexts
How expensive is time.NowMeasuring time
Fake clock, clock interface, synctestClock abstraction for tests
Cron, robfig/cron, daily jobsScheduling
timestamptz, Unix epoch, JSONPersistence of time
Persian (Jalali) calendarJalali calendar
math/rand, math/rand/v2, seeds, rand.N, ChaCha8, PCGPseudo-random numbers
Tokens, keys, crypto/randSecure randomness
strconv.ParseInt, base, bit sizeParsing integers
ParseFloat, 0.1 + 0.2, math/bigFloats and big numbers
Money, minor unitsMoney as integers
FormatFloat, %g, math helpersFormatting numbers
Which package for which jobChoosing
One process to many servicesIn architecture
Run it yourselfLab

Everything in one minute ​

ThingPlain wordsTiny exampleGotcha
time.Now()Current instant with wall and monotonic readingsstart := time.Now()Printing it shows m=+0.0123
time.Since(t)Elapsed time, immune to wall-clock jumpstime.Since(start)Use it for durations, never Now().Sub on parsed times
t.Equal(u)Same instant, any locationa.Equal(b)a == b also compares location and monotonic reading
t.IsZero()Is this the zero Timevar t time.TimeZero is year 1, not 1970
time.Durationint64 nanoseconds90 * time.Secondtime.Second * n with an int n does not compile
layoutA sample date that shows the shape"2006-01-02"YYYY-MM-DD is not a layout
time.ParseText to Time; no zone in text means UTCtime.Parse(time.DateOnly, s)Not the server's local zone
ParseInLocationText with no zone, interpreted in a zoneParseInLocation(l, s, loc)The right call for user-entered wall times
LoadLocationZone by IANA name"Asia/Tehran"Fails in scratch images without tzdata
time/tzdataEmbeds the zone database, about 450 KBimport _ "time/tzdata"Import it in main, not in libraries
TimerOne future event on a channeltime.NewTimer(d)Always Stop it or let Go 1.23 collect it
TickerRepeated eventstime.NewTicker(d)d must be positive, drops ticks for slow readers
time.AfterFuncRun a function later in its own goroutineAfterFunc(d, f)Stop does not wait for f
rand/v2 globalFast, auto-seeded, ChaCha8rand.IntN(10)Not for secrets
crypto/randOS-backed secure bytesrand.Read(b)Slower, never seed it
strconv.ParseIntText to integer with base and bit sizeParseInt(s, 10, 64)Out of range returns the clamp and an error
moneyIntegers in minor units1234 centsNever float64 for money
Go versionWhat changed for this pageWhere
1.15Ticker.ResetTimer and Ticker
1.9Transparent monotonic time inside every Timetime.Time
1.17Time.UnixMilli, UnixMicroPersistence
1.20math/rand seeds itself; rand.Seed deprecated; time.DateTime, DateOnly, TimeOnly; Time.Compare (1.20)Pseudo-random numbers, Layouts
1.22math/rand/v2; ChaCha8 in the runtime; loop variable per iterationPseudo-random numbers
1.23Timer channels unbuffered; unreferenced timers collectable; time.Tick collectableTimer and Ticker
1.24crypto/rand.Text; omitzero JSON tag; testing.B.Loop; rand.Seed is a no-opSecure randomness, Persistence, Measuring
1.25testing/synctest generally availableFake clock
MistakeSymptomSection
Comparing times with ==Equal-looking times differComparing
time.Parse for a local wall timeOff by the zone offsetParse errors
Storing local time in the databaseReports shift twice a yearUTC rule
Add(24 * time.Hour) for "tomorrow"Wrong wall time after DSTDST
time.After in a hot loop (module below go 1.23)Memory grows until each timer firesAfter
Reset without draining (module below go 1.23)Stale tick fires immediatelyTimer
math/rand for tokensPredictable secretsSecure randomness
float64 for money0.30000000000000004Money
Atoi result ignoredSilent zeroParsing integers

Why it exists ​

Time is the one input every program reads and almost nobody tests. The clock can be set backwards by NTP, a day can have 23 or 25 hours, two people in different countries mean different things by "09:00", and a program that ran fine in the developer's UTC laptop breaks in a Tehran office. Go's time package tries to make the right thing the easy thing: one type for instants, one for lengths of time, a monotonic reading hidden inside every time.Now() so elapsed time cannot go negative, and zone handling that requires you to name the zone.

Language choiceWhat you give upWhat you get
Time carries wall and monotonic readingsA simple == on timesSince and Sub survive clock changes
Duration is an int64 of nanosecondsMonths and years as durationsNo float rounding; arithmetic is integer
Layouts use a reference datestrftime-style %Y-%m-%d codesOne example doubles as documentation
Zones from the IANA database by nameOffsets such as +0330 as the modelHistory: Iran was +04:30 in summer 2022 and is +03:30 since
Timers on channelsCallbacks everywhereselect composes timeouts with cancellation
math/rand/v2 and crypto/rand as separate packagesOne "random" importA visible decision between fast and unguessable
strconv takes base and bit sizeparseInt(s) convenienceNo silent overflow, no silent octal

Everyday picture: a wall clock and a stopwatch. The wall clock tells you when to catch the bus and can be moved forward for summer time or corrected by a neighbour; the stopwatch only counts and cannot be moved. Go keeps both in the same pocket and picks the right one for each question: "what time is it?" asks the wall clock, "how long has it been?" asks the stopwatch.

Three common misunderstandings, up front ​

  1. "A time.Time is a timestamp." It is an instant plus a display zone plus, for time.Now() only, a monotonic reading. Two values for the same moment can be != and still Equal.
  2. "rand.Seed(time.Now().UnixNano()) at the top of main." That was needed before Go 1.20; today it is dead code (a no-op since Go 1.24), and it never made math/rand safe for secrets.
  3. "strconv.Atoi is enough for input." It parses base 10 only, into int (whose size depends on the platform), and the error is easy to drop. Parse with the width you will store.

Where it comes from ​

The reference-date layout comes from Go itself; the package documentation calls the American month-before-day order "a regrettable historic error". Time zone data is the IANA time zone database, maintained by volunteers and released several times a year; Iran's 2022 change is recorded in the NEWS file of release 2022b. Transparent monotonic time arrived in Go 1.9 (release notes, "Transparent Monotonic Time support"); the rest of this table is from release notes.

ChangeReleasePrimary source
math/rand auto-seeded; rand.Seed deprecatedGo 1.20go.dev/doc/go1.20
math/rand/v2 introduced; ChaCha8 and PCG; rand.N, IntNGo 1.22go.dev/doc/go1.22, go.dev/blog/randv2
Timer and Ticker channels unbuffered; unreferenced timers collectableGo 1.23go.dev/doc/go1.23
rand.Seed calls become no-ops (randseednop=0 restores)Go 1.24go.dev/doc/go1.24
testing/synctest stableGo 1.25go.dev/doc/go1.25
"Iran no longer observes DST after 2022"tzdata 2022b, 2022-08-10data.iana.org/time-zones/tzdb/NEWS

The Timer change is gated by the go line in go.mod: "These new behaviors are only enabled when the main Go program is in a module with a go.mod go line using Go 1.23.0 or later." A module on go 1.22 built with a new toolchain keeps the buffered channel and the leak, which is why every timer rule below says "go.mod".

The concept catalogue ​

time.Time: wall clock and monotonic clock Must-know ​

In plain words: time.Now() returns a value that remembers both "what the calendar says" (wall clock) and "how many nanoseconds since the process started" (monotonic clock). Subtracting two such values uses the monotonic part, so elapsed time is right even if someone changes the system date.

Common misunderstanding: "time.Now() is just a Unix timestamp." It is a struct with a wall reading, a monotonic reading and a *Location. Only the wall reading means anything outside the process, so JSON, gob, Parse, Unix and Date never carry the monotonic part.

Definition: Sub, Since, Until, Before, After, Equal and Compare use the monotonic readings when both sides have one and fall back to wall readings otherwise. In, UTC, Local, Round, Truncate and AddDate return values without a monotonic reading; Add keeps it. The documented way to strip it is t.Round(0). On some systems the monotonic clock stops while the machine sleeps, so for "time since last login" after a laptop suspend use wall times.

1  start := time.Now()               wall=10:00:00  mono=+5.000s
2  (NTP steps the wall clock back 2 min)
3  end := time.Now()                 wall=09:58:01  mono=+6.001s
4  end.Sub(start)                    1.001s   (monotonic: correct)
5  end.Unix() - start.Unix()         -119     (wall: wrong sign)
6  end.Round(0).Sub(start.Round(0))  -1m58.999s (stripped: wall again)

Real scenarios: request latency metrics; a retry loop that must wait 30 seconds; a lease that expires at a deadline (time.Until(deadline)); a token compared with time.Now().Before(exp) where exp came from JSON (no monotonic reading, so wall comparison, which is what you want).

time.Now() returns Timewall: date + clock + Locationmonotonic: ns since process startString() shows it as m=+0.0123Measuring uses monotonicSub Since Until Before AfterEqual Compare (both sides have it)Telling time uses wallFormat Year Hour Unix Add(keeps both)wall can jump: NTP, manual changeStripped: In UTC Local Round(0) Truncate AddDate JSON gob Parse Unix DateAfter stripping, == compares wall + Location only; use t.Equal(u) for the same instantThe monotonic reading never leaves the process
go
// Package monotonic shows the wall reading versus the monotonic reading of a
// time.Time, and why == is the wrong way to compare instants.
package monotonic

import (
	"encoding/json"
	"strings"
	"time"
)

// HasMonotonic reports whether t carries a monotonic reading. The String form
// prints it as "m=+0.000012345" and is the documented debugging aid.
func HasMonotonic(t time.Time) bool {
	return strings.Contains(t.String(), "m=")
}

// Strip removes the monotonic reading, the documented way: t.Round(0).
func Strip(t time.Time) time.Time { return t.Round(0) }

// RoundTripJSON marshals and unmarshals t, which drops the monotonic reading
// and normalises the location to what the string says.
func RoundTripJSON(t time.Time) (time.Time, error) {
	b, err := json.Marshal(t)
	if err != nil {
		return time.Time{}, err
	}
	var out time.Time
	err = json.Unmarshal(b, &out)
	return out, err
}

// SameInstant is the correct comparison for "do these denote the same moment".
func SameInstant(a, b time.Time) bool { return a.Equal(b) }

Comparing times and the zero time Must-know ​

In plain words: To ask "is this the same moment?" call a.Equal(b). To ask "is this value unset?" call t.IsZero().

Common misunderstanding: "a == b compares times." It compares the struct field by field: the wall and monotonic readings and the *Location pointer. The same instant expressed in two zones, or before and after a JSON round trip, is !=. A second trap: the zero time.Time is 0001-01-01 00:00:00 UTC, not the Unix epoch, and t.Unix() of it is -62135596800.

Definition: Equal reports whether the two denote the same instant ("6:00 +0200 and 4:00 UTC are Equal"). Compare (Go 1.20) returns -1, 0 or +1. Never use Time as a map key; use t.UnixNano() or a normalised value, because of the same struct comparison.

1  utc    := 2025-03-01 04:00 UTC
2  tehran := utc.In(Asia/Tehran)       06:30 +0330 (same instant)
3  utc == tehran                        false  (Location differs)
4  utc.Equal(tehran)                    true
5  var z time.Time; z.IsZero()          true;  z.Unix() == 0   false

Real scenarios: comparing updated_at from two replicas; test assertions (want.Equal(got) rather than reflect.DeepEqual); optional timestamps (omitzero, a *time.Time for "unknown"); cache keys.

go
package monotonic

import (
	"testing"
	"time"
)

func TestNowHasMonotonicAndStripRemovesIt(t *testing.T) {
	now := time.Now()
	if !HasMonotonic(now) {
		t.Fatal("time.Now must carry a monotonic reading")
	}
	if HasMonotonic(Strip(now)) {
		t.Fatal("Round(0) must strip it")
	}
	if HasMonotonic(now.UTC()) {
		t.Fatal("UTC() strips the monotonic reading too")
	}
}

func TestEqualVersusDoubleEquals(t *testing.T) {
	utc := time.Date(2025, 3, 1, 4, 0, 0, 0, time.UTC)
	plus2 := time.FixedZone("plus2", 2*3600)
	local := utc.In(plus2) // same instant, 06:00 +0200

	if utc == local {
		t.Fatal("== compares the Location pointer too, so these differ")
	}
	if !SameInstant(utc, local) {
		t.Fatal("Equal compares the instant only")
	}
}

func TestMonotonicDroppedBySerialisation(t *testing.T) {
	now := time.Now()
	back, err := RoundTripJSON(now)
	if err != nil {
		t.Fatal(err)
	}
	if HasMonotonic(back) {
		t.Fatal("JSON never carries a monotonic reading")
	}
	if now == back {
		t.Fatal("== is false: monotonic reading and Location differ")
	}
	if !now.Equal(back) {
		t.Fatalf("instants must match: %v vs %v", now, back)
	}
}

func TestZeroTime(t *testing.T) {
	var z time.Time
	if !z.IsZero() {
		t.Fatal("zero Time is January 1, year 1, 00:00:00 UTC")
	}
	if z.Unix() == 0 {
		t.Fatal("zero Time is NOT the Unix epoch")
	}
	if !time.Unix(0, 0).UTC().After(z) {
		t.Fatal("the epoch is after the zero time")
	}
}

Duration Must-know ​

In plain words: A time.Duration is a number of nanoseconds with unit constants, so 90 * time.Second reads like English and d.Minutes() converts back.

Common misunderstanding: "Durations are floats or can be multiplied by any number." They are int64. time.Second * n with an int variable does not compile (invalid operation: time.Second * n (mismatched types time.Duration and int)); convert with time.Duration(n) * time.Second. Multiplying by a float needs time.Duration(float64(d) * 1.5), and the largest Duration is about 292 years.

Definition: Nanosecond, Microsecond, Millisecond, Second, Minute, Hour are constants; there is no Day, because days vary with DST (see DST traps). ParseDuration("1h30m") accepts ns, us, µs, ms, s, m, h; "1d" fails with time: unknown unit "d" in duration "1d" and "" with time: invalid duration "". Sub saturates at the minimum or maximum Duration instead of overflowing. Round and Truncate quantise a Duration or a Time.

1  d := 90 * time.Second           // 1m30s
2  d.Seconds() -> 90, d.Minutes() -> 1.5
3  d.String() -> "1m30s"
4  d.Round(time.Minute) -> 2m0s     // rounds half away from zero
5  time.Duration(n) * time.Second   // n is an int variable

Real scenarios: HTTP client timeouts; retry delays (see Timeouts, Retries & Jitter); a TTL stored as seconds in Redis; JSON that must use whole seconds, not the default nanosecond integer.

Layouts: Format and Parse Must-know ​

In plain words: To format or parse a date, write the sample date Mon Jan 2 15:04:05 MST 2006 in the shape you want. Go reads each number in your sample as "this field goes here".

Common misunderstanding: "The layout is YYYY-MM-DD." Go does not know letters like that; the layout must use the reference digits (2006-01-02). The reference is "01/02 03:04:05PM '06 -0700", which counts 1 2 3 4 5 6 7 across month, day, hour, minute, second, year, zone. The unmatched text is treated as literal, so a wrong layout fails with a parse error rather than "working differently".

Definition: t.Format(layout) and time.Parse(layout, value). Constants: time.RFC3339 (2006-01-02T15:04:05Z07:00), time.RFC3339Nano (2006-01-02T15:04:05.999999999Z07:00), time.DateTime (2006-01-02 15:04:05), time.DateOnly, time.TimeOnly, time.Kitchen, time.RFC1123Z and the legacy ANSIC, UnixDate, RubyDate, RFC822, RFC850, Stamp. Fractions: .000 pads, .999 trims trailing zeros. RFC3339Nano "removes trailing zeros from the seconds field and thus may not sort correctly once formatted", so use a fixed .000000000 layout when strings must sort.

1  layout  2006-01-02T15:04:05Z07:00
2  Format(2025-03-09 14:05:07 UTC)    -> 2025-03-09T14:05:07Z
3  Format(+03:30 offset)              -> 2025-03-09T14:05:07+03:30
4  RFC3339Nano  .5 s  -> "...07.5Z"   .0 s -> "...07Z"   "." sorts before "Z"
5  fixed .000000000    -> "...07.500000000Z" sorts like time

Real scenarios: API responses (RFC3339), log lines, file names (20060102-150405), user-facing dates, CSV imports in DateOnly, headers (http.TimeFormat is the HTTP date format, always GMT).

Reference time: 01/02 03:04:05PM '06 -0700 (count 1 2 3 4 5 6 7)20060102150405Z07:00yearmonthdayhour 24hminutesecondzone offsetRFC3339 = 2006-01-02T15:04:05Z07:00 DateTime = 2006-01-02 15:04:05Other spellings: Jan January Mon Monday 3 03 PM .000 .999 MST -0700Trap: "YYYY-MM-DD" is not a layout; it parses as literal text and failscannot parse "..." as "..." names the first element that did not match
go
// Package layouts formats and parses times with Go's reference-time layouts.
package layouts

import (
	"fmt"
	"time"
)

// Reference time: Mon Jan 2 15:04:05 MST 2006, which is 01/02 03:04:05PM '06 -0700.
// Each field of a layout is one number from that moment.

// Common layouts, spelled out so the reader sees the digits.
const (
	ISODate     = "2006-01-02"                          // time.DateOnly
	ISODateTime = "2006-01-02 15:04:05"                 // time.DateTime
	ISO8601     = "2006-01-02T15:04:05Z07:00"           // time.RFC3339
	Nano        = "2006-01-02T15:04:05.999999999Z07:00" // time.RFC3339Nano
	// FixedNano pads to nanoseconds with 0s, so strings sort lexically.
	FixedNano = "2006-01-02T15:04:05.000000000Z07:00"
)

// FormatAll renders one instant with several layouts.
func FormatAll(t time.Time) map[string]string {
	return map[string]string{
		"RFC3339":     t.Format(time.RFC3339),
		"RFC3339Nano": t.Format(time.RFC3339Nano),
		"FixedNano":   t.Format(FixedNano),
		"DateTime":    t.Format(time.DateTime),
		"DateOnly":    t.Format(time.DateOnly),
		"Kitchen":     t.Format(time.Kitchen),
		"RFC1123Z":    t.Format(time.RFC1123Z),
		"Custom":      t.Format("Mon 2 Jan 2006, 3:04PM MST"),
	}
}

// ParseUTC parses a wall-clock string that has no zone information as UTC.
func ParseUTC(layout, value string) (time.Time, error) {
	return time.Parse(layout, value)
}

// ParseIn parses a zone-less string as wall time in loc.
func ParseIn(layout, value string, loc *time.Location) (time.Time, error) {
	return time.ParseInLocation(layout, value, loc)
}

// Describe prints the instant and its offset for lab output.
func Describe(t time.Time) string {
	name, off := t.Zone()
	return fmt.Sprintf("%s (zone %s, offset %ds)", t.Format(time.RFC3339), name, off)
}

Parse errors and ParseInLocation Must-know ​

In plain words: A parse error tells you the layout and the first place the input stopped matching. A string with no zone is read as UTC by Parse; if it was a wall time in Tehran, use ParseInLocation.

Common misunderstanding: "time.Parse uses my machine's local zone when the text has none." It uses UTC. ParseInLocation is the call that takes a zone for zone-less text, and an offset or Z in the text sets the offset (the location argument is used only when the text has no zone information, or an offset the location itself uses).

Definition and exact errors:

InputLayoutError text
2025-03-09 14:05:07time.RFC3339parsing time "2025-03-09 14:05:07" as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T"
2025-02-30time.DateOnlyparsing time "2025-02-30": day out of range
09/03/2025time.DateOnlyparsing time "09/03/2025" as "2006-01-02": cannot parse "09/03/2025" as "2006"
Asia/TeheranLoadLocationunknown time zone Asia/Teheran
"2025-05-01 08:30:00"JSON into time.Timethe same parsing time ... cannot parse " 08:30:00" as "T" message
1  time.Parse(RFC3339, "2025-03-09 14:05:07")
2  layout expects 'T' after the day; input has ' '
3  -> parsing time "..." as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T"
4  fix: choose the layout that matches the producer, or use time.DateTime

Real scenarios: a CSV from a legacy system with DD/MM/YYYY; a form field with a local date; webhook timestamps; a Laravel app sending 2025-03-09 14:05:07 (no T, no zone) to a Go service.

go
package layouts

import (
	"strings"
	"testing"
	"time"
)

func TestFormat(t *testing.T) {
	tm := time.Date(2025, 3, 9, 14, 5, 7, 120_000_000, time.UTC)
	got := FormatAll(tm)
	want := map[string]string{
		"RFC3339":     "2025-03-09T14:05:07Z",
		"RFC3339Nano": "2025-03-09T14:05:07.12Z",
		"FixedNano":   "2025-03-09T14:05:07.120000000Z",
		"DateTime":    "2025-03-09 14:05:07",
		"DateOnly":    "2025-03-09",
		"Kitchen":     "2:05PM",
		"RFC1123Z":    "Sun, 09 Mar 2025 14:05:07 +0000",
		"Custom":      "Sun 9 Mar 2025, 2:05PM UTC",
	}
	for k, w := range want {
		if got[k] != w {
			t.Errorf("%s: got %q want %q", k, got[k], w)
		}
	}
}

func TestRFC3339NanoDoesNotSortLexically(t *testing.T) {
	a := time.Date(2025, 1, 1, 0, 0, 0, 500_000_000, time.UTC) // .5
	b := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)           // no fraction
	sa, sb := a.Format(time.RFC3339Nano), b.Format(time.RFC3339Nano)
	// a is later than b, yet "...00.5Z" sorts before "...00Z" because '.' < 'Z'.
	if !a.After(b) || sa > sb {
		t.Fatalf("expected a lexical-order mismatch for %q and %q", sa, sb)
	}
	fa, fb := a.Format(FixedNano), b.Format(FixedNano)
	if !(fa > fb) {
		t.Fatalf("FixedNano must sort like time: %q %q", fa, fb)
	}
}

func TestParseErrors(t *testing.T) {
	_, err := ParseUTC(time.RFC3339, "2025-03-09 14:05:07")
	if err == nil {
		t.Fatal("expected error")
	}
	want := `parsing time "2025-03-09 14:05:07" as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T"`
	if err.Error() != want {
		t.Fatalf("got %q", err.Error())
	}

	_, err = ParseUTC(time.DateOnly, "2025-02-30")
	if err == nil || !strings.Contains(err.Error(), "day out of range") {
		t.Fatalf("Feb 30 must fail with day out of range, got %v", err)
	}

	_, err = ParseUTC(time.DateOnly, "09/03/2025")
	if err == nil || !strings.Contains(err.Error(), "cannot parse") {
		t.Fatalf("wrong layout must fail, got %v", err)
	}
}

func TestParseDefaultsToUTCNotLocal(t *testing.T) {
	tm, err := ParseUTC(time.DateTime, "2025-03-09 14:05:07")
	if err != nil {
		t.Fatal(err)
	}
	if tm.Location() != time.UTC {
		t.Fatalf("Parse without zone info must give UTC, got %v", tm.Location())
	}
}

func TestParseInLocation(t *testing.T) {
	loc := time.FixedZone("plus0330", 3*3600+1800)
	tm, err := ParseIn(time.DateTime, "2025-03-09 14:05:07", loc)
	if err != nil {
		t.Fatal(err)
	}
	if got := tm.UTC().Format(time.DateTime); got != "2025-03-09 10:35:07" {
		t.Fatalf("got %s", got)
	}
}

func TestParseOffsetKeepsFixedZone(t *testing.T) {
	tm, err := time.Parse(time.RFC3339, "2025-03-09T14:05:07+03:30")
	if err != nil {
		t.Fatal(err)
	}
	_, off := tm.Zone()
	if off != 3*3600+1800 {
		t.Fatalf("offset %d", off)
	}
	if !strings.HasPrefix(Describe(tm), "2025-03-09T14:05:07+03:30") {
		t.Fatal(Describe(tm))
	}
}

Time zones: Location, LoadLocation and time/tzdata Must-know ​

In plain words: A zone is a set of rules ("Tehran is UTC plus 3:30 now, and was plus 4:30 in summer before 2023"). time.LoadLocation("Asia/Tehran") loads the rules by name; t.In(loc) shows the same instant on that wall clock.

Common misunderstanding: "+0330 is a time zone." It is an offset at one instant. A Location carries history and future rules; time.FixedZone("x", 12600) is just an offset and knows nothing about DST. Also: time.Local is whatever the process environment says (the TZ variable or /etc/localtime), usually UTC inside containers.

Definition: time.UTC and time.Local are predefined. LoadLocation(name) looks for the IANA database in the ZONEINFO environment variable, the system's zoneinfo directories, and finally $GOROOT/lib/time/zoneinfo.zip; "" and "UTC" return UTC, "Local" returns Local. A minimal container (a scratch image, a distroless static image without tzdata) has no zoneinfo, and the call fails with unknown time zone Asia/Tehran. Importing time/tzdata (or building with -tags timetzdata) embeds the database, "will increase the size of a program by about 450 KB", and "should normally be imported by a program's main package, not by a library".

1  loc, err := time.LoadLocation("Asia/Tehran")
2  err != nil  -> unknown time zone Asia/Tehran      (name typo, or no tzdata on host)
3  import _ "time/tzdata" in main                    (embedded fallback, +450 KB)
4  t.In(loc).Format(time.RFC3339)                    2025-06-01T09:00:00+03:30
5  t.Zone()  -> ("+0330", 12600)                     abbreviation and offset seconds

Real scenarios: a Tehran-based product that shows local times; a Docker image built FROM scratch; a Lambda or Cloud Run service whose Local is UTC; loading a user's zone from their profile once and caching the *Location (it is safe for concurrent use).

go
// Package zones loads IANA zones with an embedded database and shows the DST
// traps that bite schedulers.
package zones

import (
	"fmt"
	"time"
	_ "time/tzdata" // embed the IANA database: no dependency on the host's /usr/share/zoneinfo
)

// Tehran loads Asia/Tehran. Iran observed DST until 2022 and stopped after
// 2022-09-21 (IANA tz release 2022b), so the same wall date has different
// offsets in 2022 and 2023.
func Tehran() (*time.Location, error) { return time.LoadLocation("Asia/Tehran") }

// OffsetAt returns the UTC offset in effect at t, formatted like +03:30.
func OffsetAt(t time.Time) string {
	_, off := t.Zone()
	sign := '+'
	if off < 0 {
		sign, off = '-', -off
	}
	return fmt.Sprintf("%c%02d:%02d", sign, off/3600, off%3600/60)
}

// NextDayWall adds one calendar day (same wall-clock time) using AddDate.
func NextDayWall(t time.Time) time.Time { return t.AddDate(0, 0, 1) }

// Next24h adds exactly 24 elapsed hours using Add.
func Next24h(t time.Time) time.Time { return t.Add(24 * time.Hour) }

// Instant converts a wall time in a zone to an instant, reporting whether the
// wall time existed exactly once. Go resolves gaps and overlaps silently.
func Instant(loc *time.Location, y int, m time.Month, d, h, min int) (t time.Time, exact bool) {
	t = time.Date(y, m, d, h, min, 0, 0, loc)
	// If the wall time differs from the request, the input fell into a gap
	// (spring forward) and Go shifted it; the docs do not say which way.
	exact = t.Hour() == h && t.Minute() == min
	return t, exact
}

The UTC storage rule Must-know ​

In plain words: Store and transmit instants in UTC; convert to a zone only when you show them to a person. Keep the user's zone name next to the user, not inside every timestamp.

Common misunderstanding: "I will store local time because the users are local." Local wall times are ambiguous twice a year (overlap) and missing once (gap), and they change when governments change rules, as Iran did in 2022. An instant in UTC never has those problems.

Definition: There are two kinds of future time. An instant ("the deadline is 2026-03-01T12:00:00Z") belongs in UTC. A recurring wall time ("every day at 09:00 Tehran time") must store the rule (the zone name plus the wall time) and compute instants from the current tzdata when due.

1  user types 2026-01-15 09:00 in Tehran
2  server: ParseInLocation(layout, text, tehran)  -> instant 05:30 UTC
3  store 2026-01-15T05:30:00Z in timestamptz
4  show: instant.In(user.Location)  -> 09:00 +0330
5  recurring "09:00 every day": store (zone="Asia/Tehran", hour=9, min=0), not the instant

Real scenarios: bookings, invoices due dates, audit logs, token expiries, event scheduling for several countries.

DST traps Important ​

In plain words: Clocks that spring forward skip an hour; clocks that fall back repeat one. Days are 23 or 25 hours long that day, and some wall times do not exist or exist twice.

Common misunderstanding: "A day is 24 * time.Hour." Elapsed time and calendar time differ. t.Add(24 * time.Hour) is 24 elapsed hours; t.AddDate(0, 0, 1) is the same wall clock tomorrow. Also: time.Date(...) for a gap time returns one of the neighbours and the documentation does not say which ("the choice of time zone, and therefore the time, is not well-defined"; Date "does not guarantee which"); on Go 1.27 the 02:30 that does not exist in New York on 2024-03-10 became 01:30 EST.

Definition and behaviour on 2024-03-10 / 2024-11-03 in America/New_York (real test output):

QuestionCodeResult
Same wall time tomorrowstart.AddDate(0, 0, 1)2024-03-10T12:00:00-04:00 (23 elapsed hours)
24 elapsed hoursstart.Add(24 * time.Hour)2024-03-10T13:00:00-04:00
A time inside the gaptime.Date(2024, 3, 10, 2, 30, 0, 0, ny)2024-03-10T01:30:00-05:00, not 02:30
A time inside the overlaptime.Date(2024, 11, 3, 1, 30, 0, 0, ny)first occurrence, EDT
Same 01:30 the second timefirst.Add(time.Hour)01:30 EST
Daily job at 09:00 across fall backdaily.Next25 elapsed hours; a 24-hour ticker drifts to 08:00
1  2024-03-09 12:00 EST  --AddDate(0,0,1)-->  2024-03-10 12:00 EDT   (23 h later)
2  2024-03-09 12:00 EST  --Add(24h)-------->  2024-03-10 13:00 EDT
3  2024-11-02 09:00 EDT  --next 09:00------>  2024-11-03 09:00 EST   (25 h later)

Real scenarios: a billing cron that runs twice or not at all one night a year; "daily" reports with a 23-hour window; calendar apps; a rate limit window defined as 24 * time.Hour.

Spring forward, America/New_York, 2024-03-10 (23-hour day)02:00-03:00 never occurs01:30 EST03:30 EDTAddDate: 12:00Add(24h): 13:00Fall back, 2024-11-03 (25-hour day)01:30 EDT01:30 EST (again)time.Date picks this onereach it with .Add(time.Hour)Rule: store instants in UTC; compute "same wall time tomorrow" with time.Date in the user's zone
go
package zones

import (
	"testing"
	"time"
)

func TestTehranOffsetsAroundDSTAbolition(t *testing.T) {
	loc, err := Tehran()
	if err != nil {
		t.Fatal(err)
	}
	cases := []struct {
		at   time.Time
		want string
	}{
		{time.Date(2021, 7, 1, 12, 0, 0, 0, loc), "+04:30"}, // DST in force
		{time.Date(2021, 12, 1, 12, 0, 0, 0, loc), "+03:30"},
		{time.Date(2022, 7, 1, 12, 0, 0, 0, loc), "+04:30"}, // last DST summer
		{time.Date(2023, 7, 1, 12, 0, 0, 0, loc), "+03:30"}, // no DST any more
	}
	for _, c := range cases {
		if got := OffsetAt(c.at); got != c.want {
			t.Errorf("%s: got %s want %s", c.at.Format(time.RFC3339), got, c.want)
		}
	}
}

func TestUnknownZone(t *testing.T) {
	_, err := time.LoadLocation("Asia/Teheran")
	if err == nil || err.Error() != "unknown time zone Asia/Teheran" {
		t.Fatalf("got %v", err)
	}
}

func TestAddDateVersusAddAcrossSpringForward(t *testing.T) {
	ny, err := time.LoadLocation("America/New_York")
	if err != nil {
		t.Fatal(err)
	}
	// 2024-03-10: clocks jump from 02:00 to 03:00 in New York (a 23-hour day).
	start := time.Date(2024, 3, 9, 12, 0, 0, 0, ny)

	wall := NextDayWall(start)
	if wall.Hour() != 12 || wall.Sub(start) != 23*time.Hour {
		t.Fatalf("AddDate keeps 12:00 and the day is 23h: %v (%v)", wall, wall.Sub(start))
	}
	elapsed := Next24h(start)
	if elapsed.Hour() != 13 {
		t.Fatalf("Add(24h) lands on 13:00 wall time: %v", elapsed)
	}
}

func TestGapAndOverlap(t *testing.T) {
	ny, _ := time.LoadLocation("America/New_York")

	// 02:30 on 2024-03-10 does not exist (clocks go 01:59:59 -> 03:00:00).
	got, exact := Instant(ny, 2024, time.March, 10, 2, 30)
	if exact {
		t.Fatalf("02:30 is in the gap, got %v", got)
	}
	// The documentation does not guarantee which neighbour you get. With the
	// current implementation the result is 01:30 EST (the offset before the jump).
	if got.Hour() == 2 {
		t.Fatalf("a non-existent wall time must be shifted: %v", got)
	}
	t.Logf("02:30 in the gap became %s", got.Format(time.RFC3339))

	// 01:30 on 2024-11-03 happens twice; Go returns the first (EDT).
	over, exact := Instant(ny, 2024, time.November, 3, 1, 30)
	if !exact {
		t.Fatal("01:30 exists (twice)")
	}
	if name, _ := over.Zone(); name != "EDT" {
		t.Fatalf("expected the first occurrence (EDT), got %s", name)
	}
	second := over.Add(time.Hour)
	if name, _ := second.Zone(); name != "EST" || second.Hour() != 1 {
		t.Fatalf("an hour later it is 01:30 again, in EST: %v", second)
	}
}

tzdata updates and Iran Important ​

In plain words: Governments change zone rules and the IANA database is re-released; your program is only as right as the tzdata it loaded. Iran is the textbook case: it used DST until 2022 and then stopped.

Common misunderstanding: "Time zone rules are fixed, so a server I built in 2021 still computes 2023 dates correctly." If the tzdata inside the binary (or the OS image) predates the change, the program still adds an hour to Tehran in summer 2023. The IANA NEWS for release 2022b (2022-08-10) says: "Iran no longer observes DST after 2022" and "Iran plans to stop observing DST permanently, after it falls back on 2022-09-21."

Definition: Asia/Tehran was +04:30 in summer 2021 and 2022, and is +03:30 all year since. Where the data comes from decides when you notice:

tzdata sourceHow it is updatedFailure when stale
Host OS (/usr/share/zoneinfo)OS package updates (tzdata)A long-lived VM with no updates
Container base imageRebuild the imageOld images still running
time/tzdata embeddedRebuild with a newer Go releaseA binary compiled before the change
ZONEINFO pointing to a zipYou update the fileForgotten file
PostgreSQLServer's own tz files or OSAT TIME ZONE 'Asia/Tehran' differs from the app
1  2022-07-01 12:00 Asia/Tehran  -> +04:30 (DST)
2  2023-07-01 12:00 Asia/Tehran  -> +03:30 (no DST)
3  stale tzdata (pre-2022b) says 2023-07-01 is +04:30  -> one hour off, silently

Real scenarios: an exam system with deadlines stored as Tehran wall times; reports comparing 2022 and 2023; unit tests that fix expected offsets (they pin the tzdata version in effect); regional rule changes (Chile, Egypt, Lebanon and others have changed rules at short notice).

Timer and Ticker Must-know ​

In plain words: A Timer delivers one value on its channel C after a delay. A Ticker delivers one every period. Stop cancels; Reset re-arms.

Common misunderstanding: "After Stop I must drain the channel." That was the rule before Go 1.23, because the channel had a one-element buffer and a fired-but-unread value could be received after Reset. As the Go 1.23 notes say: "the timer channel associated with a Timer or Ticker is now unbuffered, with capacity 0", so "for any call to a Reset or Stop method, no stale values prepared before that call will be sent or received after the call". This holds only when the main module says go 1.23 or later (or you do not set asynctimerchan=1).

Definition:

CallResult
time.NewTimer(d)*Timer with channel C; fires once
t.Stop()true if it stopped an active timer, false if expired or already stopped; from 1.23 a later receive blocks
t.Reset(d)re-arms; returns whether the timer was active; from 1.23 no stale value
time.NewTicker(d)repeating; d <= 0 panics with non-positive interval for NewTicker
tk.Stop(), tk.Reset(d)stop the ticks; change the period (Go 1.15)
time.After(d)<-chan Time, same as NewTimer(d).C
time.Tick(d)a Ticker channel with no handle to stop it; collectable since 1.23
time.AfterFunc(d, f)runs f in its own goroutine; Stop does not wait for f

Ticker behaviour: a slow receiver does not queue ticks; the ticker "will adjust the time interval or drop ticks to make up for slow receivers". Timer resolution on Unix is about 1 ms.

1  t := time.NewTimer(5ms)
2  ...30 ms pass, timer fired, nobody received...
3  t.Reset(200ms)
4  go 1.22 module : buffered chan still holds the old tick  -> receive returns at once
5  go 1.23+ module: tick discarded, receive blocks 200 ms; len(t.C)==cap(t.C)==0

Real scenarios: an idle timeout reset by every message (a Timer with Reset); a periodic metrics flush (Ticker plus context); a retry delay; a debouncer for file-watch events (below).

RunningNewTimer(d)Expiredvalue ready on t.CReceivedselect case ranStoppedStop() true if it was actived elapsesreceiveStop()Reset(d)Reset(d): the unread value is discarded (Go 1.23+)len(t.C) == cap(t.C) == 0receive blocks after StopBefore Go 1.23 (or asynctimerchan=1): one-slot buffer, drain after Stop, unreferenced timers not collected
go
// Package timers collects the Timer/Ticker patterns that are safe on Go 1.23+.
package timers

import (
	"context"
	"time"
)

// Sleep waits for d or until ctx is done, whichever comes first.
// time.Sleep cannot be cancelled; this can.
func Sleep(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-t.C:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// FirstWithTimeout receives from ch or gives up after d.
// The time.After inside select is collectable as soon as the function returns
// on go 1.23+ modules; on older modules it lived until it fired.
func FirstWithTimeout[T any](ch <-chan T, d time.Duration) (v T, ok bool) {
	select {
	case v = <-ch:
		return v, true
	case <-time.After(d):
		return v, false
	}
}

// Debouncer runs fn once, d after the last Trigger call. It reuses a single
// func-based Timer through Reset. Reset on an AfterFunc timer reschedules fn;
// if fn already started, Reset does not wait for it (see the Timer.Reset docs).
type Debouncer struct {
	d time.Duration
	t *time.Timer
}

// NewDebouncer creates a stopped debouncer. fn runs in its own goroutine.
func NewDebouncer(d time.Duration, fn func()) *Debouncer {
	t := time.AfterFunc(d, fn)
	t.Stop()
	return &Debouncer{d: d, t: t}
}

// Trigger (re)starts the countdown.
func (db *Debouncer) Trigger() { db.t.Reset(db.d) }

// Cancel prevents a pending run.
func (db *Debouncer) Cancel() { db.t.Stop() }

// Ticks calls fn every period until ctx is cancelled. The ticker is stopped
// by defer; the loop exits through ctx.Done().
func Ticks(ctx context.Context, period time.Duration, fn func(time.Time)) {
	tk := time.NewTicker(period)
	defer tk.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case now := <-tk.C:
			fn(now)
		}
	}
}

time.After in loops and AfterFunc Important ​

In plain words: case <-time.After(d) inside a select in a loop creates a new timer every iteration. On a module with go 1.23 or later this is fine; on older modules each unfired timer lives until it fires.

Common misunderstanding: "Go 1.23 means I never need Stop." The collection applies to timers no longer referenced and only for modules on 1.23+. A ticker you still hold keeps running, and an AfterFunc that has not fired is referenced by the runtime until it does. Use defer t.Stop() for tickers and long timers; also see Ticker leaks.

Definition: For AfterFunc(d, f), Stop returning false means "the timer has already expired and the function f has been started in its own goroutine; Stop does not wait for f to complete". Reset on an AfterFunc timer "neither waits for the prior f to complete before returning nor does it guarantee that the subsequent goroutine running f does not run concurrently with the prior one", so coordinate with a mutex or channel if f must not overlap itself.

1  for { select { case m := <-in: handle(m); case <-time.After(30*time.Second): return } }
2  go <=1.22 module: every loop iteration leaves a 30 s timer alive -> memory growth at high rate
3  go 1.23+ module : each timer is collectable once the select returns
4  safer for any version: one Timer, Reset it each loop (now correct on 1.23+)

Real scenarios: a consumer with an idle timeout; a debouncer; a watchdog that fires a callback unless petted; delayed retries of a webhook.

Sleeping and contexts Must-know ​

In plain words: time.Sleep(d) blocks the goroutine and cannot be interrupted. When the work might be cancelled (a request ended, the process is shutting down), wait on a timer and ctx.Done() in a select.

Common misunderstanding: "time.Sleep is fine in a retry loop." It ignores cancellation: a shutdown waits for the sleep, and a request whose client left keeps holding resources. Also Sleep(0) and negative values return immediately.

Definition: The pattern is a helper that returns ctx.Err() when the context wins; context.WithTimeout and context.WithDeadline use timers internally. See context for propagation and select for the multiplexing mechanics.

1  timer := time.NewTimer(d)
2  defer timer.Stop()
3  select {
4  case <-timer.C:      return nil
5  case <-ctx.Done():   return ctx.Err()   // context deadline exceeded / context canceled
6  }

Real scenarios: backoff between HTTP retries; a polling loop that must exit on SIGTERM; a worker that waits for work with a heartbeat.

Measuring time Important ​

In plain words: Use time.Since(start) for elapsed time in production code and testing.B for performance questions; do not subtract two wall-clock strings.

Common misunderstanding: "time.Now() is free." It is cheap but not free; on the machine that built this page BenchmarkNow took about 28 ns and BenchmarkSince about 12 ns (single run, Apple M4 Pro, Go 1.27.4). In a loop executing a billion times that matters; in a request handler it does not.

Definition: Go 1.24 added testing.B.Loop, the preferred benchmark loop (for b.Loop() { ... }). In that single run: Format(RFC3339) 22 ns with 1 allocation, AppendFormat into a reused buffer 16 ns with none, Parse(RFC3339) 17 ns. Time-dependent code is better tested with a clock you control than by sleeping in tests.

1  go test -run xxx -bench . -benchmem ./bench
2  BenchmarkNow-12              36792697    27.92 ns/op   0 B/op   0 allocs/op
3  BenchmarkSince-12           100000000    12.11 ns/op   0 B/op   0 allocs/op
4  BenchmarkFormatRFC3339-12    53199152    22.24 ns/op  24 B/op   1 allocs/op

Real scenarios: latency histograms; slow-query logging; profiling a hot parser; choosing AppendFormat in a log encoder.

go
package bench

import (
	"testing"
	"time"
)

// Now measures the clock read itself (wall + monotonic). Go 1.24 testing.B.Loop.
func BenchmarkNow(b *testing.B) {
	for b.Loop() {
		_ = time.Now()
	}
}

// Since is Now plus a subtraction using the monotonic reading.
func BenchmarkSince(b *testing.B) {
	start := time.Now()
	for b.Loop() {
		_ = time.Since(start)
	}
}

func BenchmarkFormatRFC3339(b *testing.B) {
	t := time.Date(2025, 5, 1, 8, 30, 0, 0, time.UTC)
	for b.Loop() {
		_ = t.Format(time.RFC3339)
	}
}

func BenchmarkParseRFC3339(b *testing.B) {
	for b.Loop() {
		_, _ = time.Parse(time.RFC3339, "2025-05-01T08:30:00Z")
	}
}

func BenchmarkAppendFormatRFC3339(b *testing.B) {
	t := time.Date(2025, 5, 1, 8, 30, 0, 0, time.UTC)
	buf := make([]byte, 0, 40)
	for b.Loop() {
		buf = t.AppendFormat(buf[:0], time.RFC3339)
	}
}

// A test file needs at least one Test for `go test` to report the package.
func TestClockMoves(t *testing.T) {
	a := time.Now()
	b := time.Now()
	if b.Before(a) {
		t.Fatal("monotonic reading went backwards")
	}
}

Clock abstraction for tests Must-know ​

In plain words: Code that calls time.Now() directly can only be tested by waiting. Pass a small Clock interface instead and give tests a clock they can move.

Common misunderstanding: "Mocking time needs a framework." For "what time is it?" a one-method interface and a 20-line fake are enough; frameworks only matter when you also want to fake timers and tickers.

Definition: Business code takes a Clock; production passes Real{}; tests pass a Fake and call Advance. For code that waits (timers, tickers, time.After), the standard library added testing/synctest (experimental in Go 1.24 behind GOEXPERIMENT=synctest, generally available in Go 1.25), which runs a test in a bubble with a fake clock that advances when every goroutine is blocked. Third-party fake clocks also exist; see Mocking with Interfaces, Dependency Injection for Testability, testify.

1  type Clock interface { Now() time.Time }
2  prod : svc := NewService(clock.Real{})
3  test : fc := clock.NewFake(2025-01-10 12:00 UTC); svc := NewService(fc)
4  fc.Advance(15 * time.Minute)      // token expires, no sleeping

Real scenarios: token and session expiry, cache TTLs, rate-limiter refills, billing periods, "trial ends in 14 days".

go
// Package clock is the smallest clock abstraction that makes time-dependent
// code testable: production code takes a Clock, tests hand it a Fake.
package clock

import (
	"sync"
	"time"
)

// Clock is what business code may ask about time.
type Clock interface {
	Now() time.Time
}

// Real reads the operating system clock.
type Real struct{}

// Now returns time.Now().
func (Real) Now() time.Time { return time.Now() }

// Fake is a manually advanced clock, safe for concurrent use.
type Fake struct {
	mu  sync.Mutex
	now time.Time
}

// NewFake starts a fake clock at t.
func NewFake(t time.Time) *Fake { return &Fake{now: t} }

// Now returns the fake instant.
func (f *Fake) Now() time.Time {
	f.mu.Lock()
	defer f.mu.Unlock()
	return f.now
}

// Advance moves the fake clock forward by d.
func (f *Fake) Advance(d time.Duration) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.now = f.now.Add(d)
}

// Token is a bearer token with an absolute expiry.
type Token struct {
	Value     string
	ExpiresAt time.Time
}

// Valid reports whether the token is still usable at the clock's current time.
func (t Token) Valid(c Clock) bool {
	return !t.ExpiresAt.IsZero() && c.Now().Before(t.ExpiresAt)
}

// Issue creates a token that lives for ttl.
func Issue(c Clock, value string, ttl time.Duration) Token {
	return Token{Value: value, ExpiresAt: c.Now().Add(ttl)}
}
go
package clock

import (
	"testing"
	"time"
)

func TestTokenExpiry(t *testing.T) {
	start := time.Date(2025, 1, 10, 12, 0, 0, 0, time.UTC)
	c := NewFake(start)
	tok := Issue(c, "abc", 15*time.Minute)

	if !tok.Valid(c) {
		t.Fatal("fresh token must be valid")
	}
	c.Advance(14*time.Minute + 59*time.Second)
	if !tok.Valid(c) {
		t.Fatal("token must still be valid one second before expiry")
	}
	c.Advance(time.Second) // exactly ExpiresAt: Before is false
	if tok.Valid(c) {
		t.Fatal("token must be invalid at the expiry instant")
	}
}

func TestZeroExpiryIsInvalid(t *testing.T) {
	var tok Token
	if tok.Valid(Real{}) {
		t.Fatal("zero Token must not be valid")
	}
}

Scheduling Important ​

In plain words: "Every day at 09:00" is a wall-clock rule, not a Ticker. Compute the next instant from the rule, sleep until it, then compute again.

Common misunderstanding: "A Ticker(24 * time.Hour) runs daily." It runs every 24 elapsed hours and drifts by an hour twice a year, forgets the schedule on restart and fires nothing at the right time of day if the process starts at 14:00.

Definition: For a simple rule use time.Date in the user's zone (the daily.Next snippet). For cron expressions use a library: github.com/robfig/cron/v3 supports cron.New(cron.WithLocation(loc)), per-schedule time zones with a CRON_TZ=Asia/Tehran 0 9 * * * prefix (its README says CRON_TZ "is now the recommended way"), and no longer recovers panics by default. In a multi-instance deployment a scheduler runs on every instance unless you add a lock or a single leader; see Distributed Locking. Persistent delayed work belongs in a queue: Retry, Backoff & Delayed Delivery.

1  now = 2025-06-01 09:00 +0330, rule = 09:00 Asia/Tehran
2  candidate = today 09:00; not after now -> tomorrow 09:00
3  wait = candidate.Sub(now)   // 24h in Tehran (no DST since 2023)
4  after the sleep: recompute from time.Now(); never add 24h to the previous run

Real scenarios: nightly reports, invoice generation on the first of the month (Jalali month start, see below), cache warming, certificate renewal checks, SLA reminders.

go
// Package daily computes the next run of a "every day at HH:MM in zone Z" job
// by working in wall-clock time, the part a cron library does for you.
package daily

import "time"

// Next returns the first instant strictly after now at which the wall clock in
// loc reads hour:minute. It builds the candidate with time.Date for the
// current and the following calendar day, so a 23- or 25-hour day does not
// shift the schedule. If a wall time does not exist on that day (DST gap) the
// result is whatever time.Date returns for it.
func Next(now time.Time, loc *time.Location, hour, minute int) time.Time {
	local := now.In(loc)
	cand := time.Date(local.Year(), local.Month(), local.Day(), hour, minute, 0, 0, loc)
	if !cand.After(now) {
		cand = time.Date(local.Year(), local.Month(), local.Day()+1, hour, minute, 0, 0, loc)
	}
	return cand
}

// Wait returns how long to sleep until the next run.
func Wait(now time.Time, loc *time.Location, hour, minute int) time.Duration {
	return Next(now, loc, hour, minute).Sub(now)
}

Persistence of time Must-know ​

In plain words: In JSON send RFC3339 strings; in PostgreSQL use timestamptz; for caches and event streams an integer Unix epoch in milliseconds is common. Each hop must agree on UTC.

Common misunderstanding: "timestamp and timestamptz are the same with and without a zone label." In PostgreSQL timestamptz converts the input to UTC and stores a point in time ("The originally stated or assumed time zone is not retained"); it prints in the session's TimeZone. timestamp stores whatever wall time you gave it and means nothing without the zone you remember separately.

Definition: PostgreSQL stores both types in 8 bytes with 1 microsecond resolution, so truncate to microseconds before comparing a Go value with what you read back. time.Time marshals to "2025-05-01T08:30:00.123+03:30" in JSON (RFC3339 with fractional seconds when present) and rejects other layouts on decode. Go 1.24 added the omitzero struct-tag option so a zero time.Time is omitted, which omitempty never did. time.Duration marshals as an integer count of nanoseconds, which is rarely what an API wants.

sql
CREATE TABLE events (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  created_at  timestamptz NOT NULL DEFAULT now(),   -- an instant, stored as UTC
  due_at      timestamptz,                          -- NULL = unset
  zone_name   text NOT NULL DEFAULT 'Asia/Tehran',  -- how to show it, not what it is
  due_wall    time                                  -- recurring "09:00" rule, with zone_name
);
-- show in a zone without touching the application
SELECT created_at AT TIME ZONE 'Asia/Tehran' FROM events;
1  Go time.Time (any zone)  -> ToStore: UTC, Round(0), Truncate(µs)
2  INSERT ... $1            -> pgx sends the instant; timestamptz keeps UTC
3  JSON out                 -> "2025-05-01T08:30:00.123+03:30" (offset kept as sent)
4  epoch ms 1746075600000   -> time.UnixMilli(ms) is in Local; call .UTC() before formatting

Real scenarios: created_at columns; JWT exp claims (Unix seconds, see JWT Deep Dive); Kafka record timestamps in epoch milliseconds; CSV exports for finance. Column design is in Schema Design, Normalization & Data Types and time-ordered identifiers in ID Generation at Scale.

go
// Package persist shows how a time.Time leaves the process: JSON, Unix
// epoch integers, and the UTC-in, local-out rule.
package persist

import (
	"encoding/json"
	"time"
)

// Event is the shape an API would return. Times are stored and sent as UTC
// instants; the zone a user sees is a presentation concern.
type Event struct {
	ID        string     `json:"id"`
	CreatedAt time.Time  `json:"created_at"`
	ClosedAt  time.Time  `json:"closed_at,omitzero"` // Go 1.24: omit the zero Time
	DeletedAt *time.Time `json:"deleted_at"`         // nil pointer encodes as null
	TTL       Seconds    `json:"ttl"`
}

// Seconds marshals a duration as whole seconds, because time.Duration would
// otherwise encode as an int64 count of nanoseconds.
type Seconds time.Duration

// MarshalJSON writes the duration as whole seconds.
func (s Seconds) MarshalJSON() ([]byte, error) {
	return json.Marshal(int64(time.Duration(s) / time.Second))
}

// UnmarshalJSON reads whole seconds.
func (s *Seconds) UnmarshalJSON(b []byte) error {
	var n int64
	if err := json.Unmarshal(b, &n); err != nil {
		return err
	}
	*s = Seconds(time.Duration(n) * time.Second)
	return nil
}

// ToStore normalises a time before it is written to a timestamptz column or a
// cache: UTC, no monotonic reading, microsecond precision (PostgreSQL's limit).
func ToStore(t time.Time) time.Time {
	return t.UTC().Round(0).Truncate(time.Microsecond)
}

// EpochMillis is the integer form used by JavaScript clients and Kafka timestamps.
func EpochMillis(t time.Time) int64 { return t.UnixMilli() }

// FromEpochMillis rebuilds an instant from milliseconds. The result is in the
// Local location, so call UTC() or In(loc) before formatting.
func FromEpochMillis(ms int64) time.Time { return time.UnixMilli(ms) }

Jalali calendar Good to know ​

In plain words: The standard library knows only the Gregorian calendar ("The calendrical calculations always assume a Gregorian calendar, with no leap seconds"). Persian (Solar Hijri, Jalali) dates are a presentation layer on top of the same instant.

Common misunderstanding: "Store Jalali dates in the database." Store the instant (or a Gregorian date) and convert at the edge. Jalali months have between 29 and 31 days, a Jalali year starts at Nowruz, and "the first day of the month" or "end of the year" must be converted before it becomes a query bound.

Definition: In Go use a library such as github.com/yaa110/go-persian-calendar ("The implementation of Persian (Solar Hijri) Calendar in Go"); in PHP, morilog/jalali (Jalali dates for PHP) or ICU's persian calendar through IntlDateFormatter. Third-party code: pin versions and test month boundaries and leap years yourself. Convert the instant with the library, format the Jalali fields, and never do date arithmetic on Jalali components by hand.

1  instant 2025-03-21T00:30:00Z -> In(Asia/Tehran) 2025-03-21 04:00 +0330
2  Gregorian date 2025-03-21 -> Jalali 1404-01-01 (Nowruz) by library, not by arithmetic
3  query bound for "Farvardin 1404": [2025-03-21 00:00 Tehran, 2025-04-21 00:00 Tehran)

Real scenarios: invoices and reports for Iranian customers; "monthly" subscriptions anchored to a Jalali day; user-facing date pickers; accounting periods.

Pseudo-random numbers: math/rand and math/rand/v2 Must-know ​

In plain words: math/rand/v2 gives fast random numbers for jitter, sampling, shuffling and tests. It is the one to import in new code; the older math/rand still works.

Common misunderstanding: "I must call rand.Seed(time.Now().UnixNano())." Since Go 1.20 the global generator seeds itself randomly; since Go 1.24 calls to the deprecated rand.Seed do nothing ("To restore the old behavior use GODEBUG setting randseednop=0"). math/rand/v2 has no global Seed at all. To repeat a sequence, create your own generator with an explicit seed.

Definition:

Piecemath/rand (v1)math/rand/v2
Global generatorauto-seeded since 1.20auto-seeded, ChaCha8, always
Seed functionrand.Seed (deprecated, no-op since 1.24)none; use rand.New(src)
Ints in rangeIntn(n), Int63n(n)IntN(n), Int64N(n), Uint64N(n)
Generic helpernonerand.N(max) for any integer type, including time.Duration
Algorithmsthe Go 1 generator (about 5 KB of state)PCG (16 bytes of state), ChaCha8
Shuffle and permutationShuffle, PermShuffle, Perm
Concurrencyglobal is safe; *Rand is notglobal is safe; *Rand is not

The v2 post explains the motivation: "the repeatability requirement in math/rand meant that we couldn't replace the generator there"; v2 "made ChaCha8 the default generator used in global functions" so that "accidentally using math/rand/v2 is not as catastrophic as using math/rand would be", but "Programs are still strongly encouraged to use crypto/rand to generate cryptographic secrets". Build a reproducible generator with rand.New(rand.NewPCG(seed1, seed2)) or rand.New(rand.NewChaCha8(seed32bytes)), and rand.N(5 * time.Second) replaces time.Duration(rand.Int63n(int64(5*time.Second))).

1  r := rand.New(rand.NewPCG(1, 2))
2  r.IntN(100) x5            -> 76 61 78 79 23     (same on every run, real output)
3  rand.N(50 * time.Millisecond)   -> jitter in [0, 50ms)
4  rand.Shuffle(len(xs), func(i, j int) { xs[i], xs[j] = xs[j], xs[i] })
5  never share one *Rand between goroutines without a lock

Real scenarios: exponential backoff with full jitter (Timeouts, Retries & Jitter); choosing a replica; sampling 1% of requests for tracing; deterministic simulations and property tests; shuffling a playlist.

Need a random valueWould a guess cause harm?crypto/randtokens, keys, reset codesrand.Read, rand.Text, rand.IntOS entropy, no seedmath/rand/v2 + PCGmust repeat: tests, simulationsrand.New(rand.NewPCG(s1, s2))or NewChaCha8(seed)math/rand/v2 globaljitter, sampling, shufflerand.IntN, rand.N, Shuffleauto-seeded ChaCha8yesno, same seedno, any valuev2 has no global Seed; v1 auto-seeds since Go 1.20 and rand.Seed is a no-op since Go 1.24
go
// Package random shows math/rand/v2 for simulation and jitter, and crypto/rand
// for anything an attacker must not guess.
package random

import (
	"crypto/rand"
	"fmt"
	"math/big"
	mrand "math/rand/v2"
	"time"
)

// Deterministic returns a reproducible generator: same seeds, same sequence.
// Use it in tests and simulations. It is NOT secure.
func Deterministic(seed1, seed2 uint64) *mrand.Rand {
	return mrand.New(mrand.NewPCG(seed1, seed2))
}

// DeterministicChaCha is the same idea with the ChaCha8 generator (32-byte seed).
func DeterministicChaCha(seed [32]byte) *mrand.Rand {
	return mrand.New(mrand.NewChaCha8(seed))
}

// Jitter returns a duration in [0, max) using the auto-seeded global generator.
// rand.N works on any integer type, including time.Duration.
func Jitter(max time.Duration) time.Duration {
	return mrand.N(max)
}

// Backoff is exponential backoff with full jitter: random in [0, base*2^attempt),
// capped at limit.
func Backoff(attempt int, base, limit time.Duration) time.Duration {
	ceiling := base << attempt
	if ceiling <= 0 || ceiling > limit { // <= 0 catches shift overflow
		ceiling = limit
	}
	return mrand.N(ceiling)
}

// Pick returns a random element index in [0, n) for a shard or replica choice.
func Pick(n int) int { return mrand.IntN(n) }

// Shuffled returns a shuffled copy, leaving in untouched.
func Shuffled[T any](in []T) []T {
	out := append([]T(nil), in...)
	mrand.Shuffle(len(out), func(i, j int) { out[i], out[j] = out[j], out[i] })
	return out
}

// SecretToken returns n random bytes from crypto/rand as hex. It never uses
// math/rand: session ids, reset tokens and API keys must be unpredictable.
func SecretToken(n int) (string, error) {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return fmt.Sprintf("%x", b), nil
}

// SecretText returns a base32 string with at least 128 bits of randomness
// (crypto/rand.Text, Go 1.24+): good for invite codes and reset tokens.
func SecretText() string { return rand.Text() }

// SecretIntN returns a uniform value in [0, max) from crypto/rand.
func SecretIntN(max int64) (int64, error) {
	v, err := rand.Int(rand.Reader, big.NewInt(max))
	if err != nil {
		return 0, err
	}
	return v.Int64(), nil
}

// OneTimeCode returns a six-digit code, zero padded, from crypto/rand.
func OneTimeCode() (string, error) {
	v, err := SecretIntN(1_000_000)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%06d", v), nil
}

Secure randomness: crypto/rand Must-know ​

In plain words: Anything an attacker must not guess (session ids, reset tokens, API keys, nonces, one-time codes) comes from crypto/rand, which reads the operating system's secure generator.

Common misunderstanding: "ChaCha8 is cryptographically strong, so v2 is fine for tokens." The v2 global generator uses ChaCha8, but it is seeded at process start and its output is meant for general use; the Go team still says to use crypto/rand for secrets. Also: crypto/rand.Reader needs no seed, and in current Go rand.Read "never returns an error".

Definition: rand.Read(b) fills bytes; rand.Text() (Go 1.24) returns a base32 string with at least 128 bits of randomness; rand.Int(rand.Reader, max) returns a uniform *big.Int in [0, max) (it panics if max <= 0). Use Int with modulus arithmetic done correctly: Read then % n introduces bias unless n divides the range. On Linux the reader uses getrandom(2), on macOS arc4random_buf, on Windows ProcessPrng.

1  b := make([]byte, 16); rand.Read(b)       // 128 bits
2  token := rand.Text()                      // 26 base32 characters, >= 128 bits
3  v, _ := rand.Int(rand.Reader, big.NewInt(1_000_000))   // uniform in [0, 10^6)
4  fmt.Sprintf("%06d", v)                    // one-time code, zero padded

Real scenarios: password-reset links, API keys, CSRF tokens, salts (see Hashing & Crypto), OTP codes, idempotency keys.

Parsing integers: strconv Must-know ​

In plain words: strconv.ParseInt(s, base, bitSize) turns text into an integer and tells you if it was not a number or did not fit. Atoi(s) is ParseInt(s, 10, 0) shorthand.

Common misunderstanding: "ParseInt returns an error and zero when the number is too big." It returns an error and the clamped maximum (or minimum) value of that bit size, so ignoring the error gives a plausible wrong number. And bitSize does not change the return type; the result is always int64, only checked against the narrower range.

Definition: base is 0 or 2 to 36; base 0 reads the prefix (0b, 0o, 0x, a leading 0) and allows underscores (1_000), other bases do not. bitSize 0, 8, 16, 32, 64 means int, int8 and so on. The error is a *strconv.NumError wrapping strconv.ErrSyntax or strconv.ErrRange, so use errors.Is. Unsigned: ParseUint; booleans: ParseBool (accepts 1, t, T, TRUE, true, True and the false forms).

CallResult
ParseInt("42", 10, 64)42
ParseInt("ff", 16, 64)255
ParseInt("0xff", 0, 64)255 (prefix chooses base)
ParseInt("1_000", 0, 64)1000; with base 10 it is invalid syntax
ParseInt("-128", 10, 8)-128
ParseInt("128", 10, 8)127 and strconv.ParseInt: parsing "128": value out of range
ParseInt("abc", 10, 64)0 and strconv.ParseInt: parsing "abc": invalid syntax
ParseInt("9223372036854775808", 10, 64)9223372036854775807 and value out of range
1  n, err := strconv.ParseInt(s, 10, 32)
2  errors.Is(err, strconv.ErrSyntax)   // not a number: 400 Bad Request
3  errors.Is(err, strconv.ErrRange)    // too large: 400 or 422, say which field
4  int32(n)                            // safe: already range checked

Real scenarios: query-string and path parameters (net/http); environment variables and flags; CSV imports; parsing a port or a byte count; reading an ID from a URL.

go
// Package numbers parses and formats numbers, and handles money as integer
// minor units.
package numbers

import (
	"errors"
	"fmt"
	"math/big"
	"strconv"
	"strings"
)

// Parse shows the three arguments of ParseInt: text, base, bit size.
func Parse(s string, base, bits int) (int64, error) {
	return strconv.ParseInt(s, base, bits)
}

// IsRange reports whether err is a "value out of range" error from strconv.
func IsRange(err error) bool { return errors.Is(err, strconv.ErrRange) }

// IsSyntax reports whether err is an "invalid syntax" error from strconv.
func IsSyntax(err error) bool { return errors.Is(err, strconv.ErrSyntax) }

// FloatDrift returns 0.1+0.2 and whether it equals 0.3. It does not.
func FloatDrift() (float64, bool) {
	a, b := 0.1, 0.2
	sum := a + b
	return sum, sum == 0.3
}

// Format shows the common ways to turn a float64 into text.
func Format(f float64) map[string]string {
	return map[string]string{
		"FormatFloat f -1":      strconv.FormatFloat(f, 'f', -1, 64), // shortest exact round-trip
		"FormatFloat f 2":       strconv.FormatFloat(f, 'f', 2, 64),
		"FormatFloat e 3":       strconv.FormatFloat(f, 'e', 3, 64),
		"FormatFloat g -1":      strconv.FormatFloat(f, 'g', -1, 64),
		"Sprintf %g":            fmt.Sprintf("%g", f),
		"Sprintf %.2f":          fmt.Sprintf("%.2f", f),
		"FormatFloat f -1 / 32": strconv.FormatFloat(f, 'f', -1, 32),
	}
}

// ParseMinor converts a decimal string such as "12.34" into integer minor
// units (cents, or rials for a currency with 0 decimals) without touching
// float64. decimals is the currency exponent (2 for USD, 0 for IRR).
func ParseMinor(s string, decimals int) (int64, error) {
	neg := strings.HasPrefix(s, "-")
	s = strings.TrimPrefix(s, "-")
	whole, frac, hasDot := strings.Cut(s, ".")
	if whole == "" || (hasDot && frac == "") || len(frac) > decimals {
		return 0, fmt.Errorf("money %q: want at most %d decimals: %w", s, decimals, strconv.ErrSyntax)
	}
	frac += strings.Repeat("0", decimals-len(frac))
	n, err := strconv.ParseInt(whole+frac, 10, 64)
	if err != nil {
		return 0, err
	}
	if neg {
		n = -n
	}
	return n, nil
}

// FormatMinor is the inverse of ParseMinor.
func FormatMinor(n int64, decimals int) string {
	sign := ""
	if n < 0 {
		sign, n = "-", -n
	}
	if decimals == 0 {
		return sign + strconv.FormatInt(n, 10)
	}
	s := strconv.FormatInt(n, 10)
	for len(s) <= decimals {
		s = "0" + s
	}
	return sign + s[:len(s)-decimals] + "." + s[len(s)-decimals:]
}

// Factorial uses math/big where int64 would overflow at 21!.
func Factorial(n int64) *big.Int {
	out := big.NewInt(1)
	for i := int64(2); i <= n; i++ {
		out.Mul(out, big.NewInt(i))
	}
	return out
}

// SplitEvenly divides total minor units into n parts without losing a cent:
// the first total%n parts get one extra unit.
func SplitEvenly(total int64, n int) []int64 {
	parts := make([]int64, n)
	base, rem := total/int64(n), total%int64(n)
	for i := range parts {
		parts[i] = base
		if int64(i) < rem {
			parts[i]++
		}
	}
	return parts
}
go
package numbers

import (
	"math"
	"slices"
	"testing"
)

func TestParseBasesAndBitSizes(t *testing.T) {
	cases := []struct {
		s          string
		base, bits int
		want       int64
		errText    string
	}{
		{"42", 10, 64, 42, ""},
		{"ff", 16, 64, 255, ""},
		{"0xff", 0, 64, 255, ""}, // base 0: prefix decides
		{"0b101", 0, 64, 5, ""},
		{"0o17", 0, 64, 15, ""},
		{"1_000", 0, 64, 1000, ""}, // underscores only with base 0
		{"-128", 10, 8, -128, ""},
		{"128", 10, 8, 127, `strconv.ParseInt: parsing "128": value out of range`},
		{"abc", 10, 64, 0, `strconv.ParseInt: parsing "abc": invalid syntax`},
		{"", 10, 64, 0, `strconv.ParseInt: parsing "": invalid syntax`},
		{"1_000", 10, 64, 0, `strconv.ParseInt: parsing "1_000": invalid syntax`},
	}
	for _, c := range cases {
		got, err := Parse(c.s, c.base, c.bits)
		switch {
		case c.errText == "" && err != nil:
			t.Errorf("%q: unexpected error %v", c.s, err)
		case c.errText != "" && (err == nil || err.Error() != c.errText):
			t.Errorf("%q: error %v, want %s", c.s, err, c.errText)
		case got != c.want:
			t.Errorf("%q: got %d want %d", c.s, got, c.want)
		}
	}
	_, err := Parse("128", 10, 8)
	if !IsRange(err) || IsSyntax(err) {
		t.Fatal("classification by errors.Is failed")
	}
}

func TestAtoiMessageAndLargeValues(t *testing.T) {
	// A value that does not fit int64 returns the clamped max, plus an error.
	got, err := Parse("9223372036854775808", 10, 64)
	if got != math.MaxInt64 || !IsRange(err) {
		t.Fatalf("got %d, %v", got, err)
	}
}

func TestFloatDrift(t *testing.T) {
	sum, eq := FloatDrift()
	if eq || sum == 0.3 {
		t.Fatal("0.1+0.2 must not equal 0.3 in float64")
	}
	if got := Format(sum)["FormatFloat f -1"]; got != "0.30000000000000004" {
		t.Fatalf("got %s", got)
	}
}

func TestFormatFloat(t *testing.T) {
	m := Format(1234.5678)
	want := map[string]string{
		"FormatFloat f -1":      "1234.5678",
		"FormatFloat f 2":       "1234.57",
		"FormatFloat e 3":       "1.235e+03",
		"FormatFloat g -1":      "1234.5678",
		"Sprintf %g":            "1234.5678",
		"Sprintf %.2f":          "1234.57",
		"FormatFloat f -1 / 32": "1234.5677",
	}
	for k, w := range want {
		if m[k] != w {
			t.Errorf("%s: got %s want %s", k, m[k], w)
		}
	}
	if got := Format(1e21)["Sprintf %g"]; got != "1e+21" {
		t.Fatalf("%%g switches to exponent form for large exponents: %s", got)
	}
}

func TestMinorUnits(t *testing.T) {
	cases := []struct {
		in       string
		decimals int
		want     int64
	}{
		{"12.34", 2, 1234},
		{"12", 2, 1200},
		{"0.05", 2, 5},
		{"-0.99", 2, -99},
		{"1500000", 0, 1500000}, // rials have no minor unit in practice
	}
	for _, c := range cases {
		got, err := ParseMinor(c.in, c.decimals)
		if err != nil || got != c.want {
			t.Errorf("%q: got %d, %v want %d", c.in, got, err, c.want)
		}
		if back := FormatMinor(got, c.decimals); c.decimals == 2 && c.in != "12" && back != c.in {
			t.Errorf("round trip %q -> %q", c.in, back)
		}
	}
	for _, bad := range []string{"12.345", "1.", ".5", "", "1,5"} {
		if _, err := ParseMinor(bad, 2); err == nil {
			t.Errorf("%q must be rejected", bad)
		}
	}
}

func TestSplitEvenlyKeepsEveryCent(t *testing.T) {
	got := SplitEvenly(1000, 3)
	if !slices.Equal(got, []int64{334, 333, 333}) {
		t.Fatalf("got %v", got)
	}
	var sum int64
	for _, p := range got {
		sum += p
	}
	if sum != 1000 {
		t.Fatal("cents lost")
	}
}

func TestBigFactorial(t *testing.T) {
	if got := Factorial(21).String(); got != "51090942171709440000" {
		t.Fatalf("21! = %s", got)
	}
	if Factorial(21).IsInt64() {
		t.Fatal("21! does not fit int64")
	}
	if got := Factorial(20).Int64(); got != 2432902008176640000 {
		t.Fatalf("20! = %d", got)
	}
}

Floats, ParseFloat and math/big Must-know ​

In plain words: float64 stores binary fractions, so many decimals (0.1, 0.2, 12.34) are approximations. ParseFloat gives you the nearest one. math/big gives exact integers, rationals and arbitrary-precision floats.

Common misunderstanding: "0.1 + 0.2 == 0.3." It is false in Go, Rust, JavaScript and PHP alike: the sum prints as 0.30000000000000004. Compare floats with a tolerance, never with ==, and never use them for money.

Definition: strconv.ParseFloat(s, 64) returns the closest float64 (32 rounds to float32), accepts inf, nan, exponents and hexadecimal floats, and returns ErrRange with ±Inf on overflow. math.IsNaN, math.IsInf test the specials, and NaN != NaN. math/big types: big.Int (exact integers, e.g. 21! which overflows int64), big.Rat, big.Float. They are mutable receivers (z.Mul(x, y) stores into z).

1  0.1 + 0.2                    -> 0.30000000000000004
2  float64(16777217)            exact; float32(16777217) -> 1.6777216e+07 (rounds)
3  20! = 2432902008176640000    fits int64
4  21! = 51090942171709440000   needs big.Int

Real scenarios: parsing measurements; scientific results; factorials and combinatorics; cryptographic key sizes (big.Int); anything where the digit count matters.

Money as integers (minor units) Must-know ​

In plain words: Keep money as whole numbers of the smallest unit (cents, or rials for a currency used without fractions) and split or round it yourself.

Common misunderstanding: "float64 with two decimals is accurate enough." It drifts, accumulates errors across sums and compares unequal to the amount the customer saw. A decimal library helps in some cases, but the baseline rule is integers in minor units plus a stored currency code.

Definition: Parse "12.34" by string splitting, never through a float: ParseMinor("12.34", 2) is 1234. Rejecting more decimals than the currency allows (12.345) is a validation error, not a rounding opportunity. Division must decide who gets the remainder: SplitEvenly(1000, 3) is [334 333 333], so no cent disappears. In SQL use bigint minor units (or numeric(19, 4) when you must), never real or double precision.

1  "12.34"        -> ParseMinor(.., 2) -> 1234 (int64)
2  1234 + 566     -> 1800  (exact)
3  1000 split 3   -> [334 333 333]   sum 1000
4  FormatMinor(1800, 2) -> "18.00"
5  currency stored next to the amount: (1800, "USD"), (1500000, "IRR")

Real scenarios: carts and orders, wallet balances, tax lines, invoice splits, ledgers (Schema Design, Normalization & Data Types, ACID & Transactions).

Formatting numbers and the math helpers Important ​

In plain words: strconv.FormatFloat(f, fmt, precision, bitSize) and fmt verbs turn numbers into text; math has the rounding and limits helpers.

Common misunderstanding: "%v and %g print the same thing as %f." %g uses the shortest representation and switches to exponent form for large or small exponents (1e+21), %f never does, and %.2f rounds the binary value, not the decimal you typed.

Definition:

Call1234.5678 becomes
FormatFloat(f, 'f', -1, 64)1234.5678 (shortest text that round-trips)
FormatFloat(f, 'f', 2, 64)1234.57
FormatFloat(f, 'e', 3, 64)1.235e+03
FormatFloat(f, 'g', -1, 64)1234.5678
Sprintf("%g", 1e21)1e+21
FormatFloat(f, 'f', -1, 32)1234.5677 (a float32 has fewer digits)

math helpers: Floor, Ceil, Round (half away from zero), RoundToEven, Trunc, Abs, Min, Max (and the min/max built-ins), Pow, Sqrt, Mod, MaxInt64, MaxInt32, Inf, NaN. For grouped output (1,234.57) use golang.org/x/text/message, see Strings, Runes, fmt Verbs, text/template & regexp.

1  strconv.FormatInt(255, 2)  -> "11111111"      strconv.FormatInt(255, 16) -> "ff"
2  strconv.Itoa(42)           -> "42"
3  fmt.Sprintf("%08.3f", 3.14159) -> "0003.142"
4  math.Round(2.5) -> 3   math.RoundToEven(2.5) -> 2

Real scenarios: log lines, CSV exports, human-readable sizes, percentage displays, rounding a computed fee.

Mechanics ​

Error and panic texts you will see Must-know ​

SituationExact text
Layout mismatchparsing time "2025-03-09 14:05:07" as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T"
Impossible dateparsing time "2025-02-30": day out of range
Unknown zoneunknown time zone Asia/Teheran
Bad duration unittime: unknown unit "d" in duration "1d"
Empty durationtime: invalid duration ""
Non-positive tickerpanic: non-positive interval for NewTicker
Duration times intinvalid operation: time.Second * n (mismatched types time.Duration and int)
Out of range intstrconv.ParseInt: parsing "128": value out of range
Not a numberstrconv.Atoi: parsing "abc": invalid syntax
Context done during waitcontext deadline exceeded or context canceled
Timer misuse in old modulesstale value received immediately after Reset (no message, just a wrong tick)

Version gates and GODEBUG settings Must-know ​

SettingEffectDefault
go 1.23 in go.modNew timer semanticson for modules at 1.23+
GODEBUG=asynctimerchan=1Back to buffered timer channelsoff
GODEBUG=randseednop=0rand.Seed works againno-op since Go 1.24
GODEBUG=randautoseed=0Old fixed global seed for math/rand (Go 1.20)auto-seeded
ZONEINFO=/path/zoneinfo.zipWhere LoadLocation looks firstunset
-tags timetzdataEmbed tzdata at build timenot embedded
TZ=Asia/TehranSets time.Local for the processsystem setting

How the layout parser reads Good to know ​

The layout is tokenised left to right; each recognised element (2006, 01, Jan, Mon, 15, PM, Z07:00, .000) consumes input and everything else must match literally. Parse rejects leftover input (...: extra text: "..."), validates ranges (day out of range, month out of range, hour out of range) and, when parsing only, accepts a fractional second right after the seconds field even if the layout has none, which is why an RFC3339 layout parses 2025-05-01T08:30:00.123Z.

Timer internals in one paragraph Good to know ​

Timers live in per-processor heaps managed by the runtime; resolution is bounded by the OS timer (about 1 ms on Unix, about 0.5 ms on Windows 1803+). With the Go 1.23 implementation the channel has capacity zero and a pending send happens at receive time, which is why len(t.C) and cap(t.C) are 0 and why Stop and Reset can guarantee no stale value. Polling len(t.C) to see if a timer fired must become a non-blocking select receive.

Solving the classic problems ​

ProblemSolutionHowCost or limit
Elapsed time wrong after clock changetime.Sincemonotonic readingNot valid across processes or restarts
Same instant compares unequalEqual or Compareinstant-only comparisonNone
Zone-less text off by hoursParseInLocationpass the user's *LocationNeeds a zone per user
LoadLocation fails in containersimport _ "time/tzdata"embedded database+450 KB, update on Go upgrade
Wrong daily schedule on DST dayscompute with time.Date in the zonerule, not intervalGap times need a policy
Hung sleep on shutdownselect on timer and ctx.Done()helper Sleep(ctx, d)None
Stale ticks after Resetgo.mod at 1.23 or laterunbuffered channelOld modules keep the old behaviour
Timers in testsClock interface, synctestfake timeFakes must implement every call you use
Predictable tokenscrypto/randOS entropySlower than math/rand
Unrepeatable simulationrand.New(rand.NewPCG(a, b))explicit seedsNot safe for concurrent use
Silent overflow on parseParseInt(s, 10, 32)explicit widthHandle ErrRange
Float moneyintegers in minor unitsParseMinorCurrency exponent per currency

A clock you can move, in a test Must-know ​

The clock snippet above is the entire pattern. In production code a type receives a Clock in its constructor; in a test, fc.Advance(14*time.Minute + 59*time.Second) and fc.Advance(time.Second) prove the exact boundary (a token valid before and invalid at ExpiresAt). For goroutines that sleep, the same test can run inside synctest.Test on Go 1.25 so that time.Sleep(time.Hour) returns instantly.

Debouncing with one reusable timer Important ​

Debouncer in the timers snippet creates an AfterFunc timer, stops it, and calls Reset on each trigger; a burst of five triggers inside 30 ms runs the callback once. The documented caveat for func timers applies: if f already started, Reset does not wait for it, so f must be safe to run again while the previous run finishes.

Jitter and backoff Important ​

Backoff(attempt, base, limit) returns a random delay in [0, min(limit, base*2^attempt)) using rand.N; the shift is guarded because base << attempt overflows int64 around attempt 63 (the test uses attempt 80). Full jitter spreads many clients so they do not retry in lockstep; see Timeouts, Retries & Jitter.

Testing time-dependent code Must-know ​

Test goalTechnique
Expiry boundaryFake.Advance to one tick before and exactly at the deadline
DST behaviourtime.Date in America/New_York, assert offsets, not just hours
Parse errorsassert the exact error text only for stable cases; prefer errors.As for *time.ParseError
Random behaviourseed rand.NewPCG; assert ranges for global generators
Timersshort real durations with generous margins, or synctest
tzdata driftpin expected offsets for known dates; run tests with -tags timetzdata in CI

Choosing ​

SituationUseExtra techniqueReason
Elapsed time in one processtime.Since(start)Duration.Round for logsMonotonic reading
Time shown to a persont.In(userLoc).Format(...)cache *Location per userZone is a display concern
Timestamp in an APIRFC3339 in UTComitzero for optional timesUnambiguous, sortable if fixed width
Timestamp in PostgreSQLtimestamptzmicrosecond truncationStored as UTC
Daily/weekly schedulezone plus wall rulecron library with CRON_TZDST and rule changes
One-shot delayNewTimer with Stopselect with ctx.Done()Cancellation
Periodic workNewTickerdefer tk.Stop()Releases the ticker
Deadline in a call chaincontext.WithTimeoutcheck ctx.Err()Propagates across layers
Shuffle, jitter, samplingmath/rand/v2rand.N for durationsFast, no seeding
Reproducible random test datarand.New(rand.NewPCG(a, b))log the seedsReplay failures
Secrets and tokenscrypto/randrand.Text()Unguessable
Parse user integersParseInt(s, 10, bits)errors.Is on the errorWidth and failure are explicit
Moneyint64 minor unitscurrency code columnExact
Huge exact numbersmath/bigavoid in hot loopsAllocation

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One clock, one Local zone, one tzdata. The simple correct usage: instants in UTC in the database (timestamptz), time.Since for latency, a Clock interface in the handful of types that care about "now", crypto/rand for tokens and math/rand/v2 for jitter. A Laravel monolith keeps config('app.timezone') at UTC and converts per user in the view layer; a Go service does the same with a per-user *Location.

Modular monolith and multiple databases ​

Every module reads time through the same injected Clock, so one test can move the whole application. Each database stores UTC; a billing module and a reporting module that disagree about "end of month" are comparing local month boundaries, so define the boundary once (a function that takes a *Location). Zone rules for the application and for PostgreSQL's AT TIME ZONE must come from the same tzdata release or reports will differ by an hour on rule-change dates.

Microservices ​

1  service A  stamps event.created_at = now.UTC()   (RFC3339 in the message)
2  broker     delivers (hours later, out of order)
3  service B  parses with time.Parse(time.RFC3339)  -> instant; compares with its own clock
4  clock skew between hosts is typically milliseconds; an NTP step can be larger
5  never trust the sender's clock for ordering; use the broker offset or a sequence

Each service has its own clock, its own tzdata and its own go.mod version, so a timer behaves differently in a service still on go 1.22. Deadlines cross the wire as a duration (gRPC timeout, context deadline), not as an absolute time, because absolute times need synchronised clocks. Retries need jitter and idempotency: Idempotent Consumers & the Inbox Pattern, API Idempotency. Causality across services is not the wall clock's job: Vector Clocks, Lamport Clocks & Causality.

Distributed data: replicas, caches, NAT and containers ​

Replica lag means now() on the replica is not "now" for the data: a cache entry with a 60-second TTL set from created_at + 60s can already be expired when the replica applies the row (Replication, Read Replicas & Failover). Distributed SQL systems use hybrid or true-time clocks to order transactions (Distributed SQL, Consensus & 2PC); an application timestamp is not that. In containers time.Local is UTC unless you set TZ, and a minimal image has no tzdata, so embed it. Lease-based locks fail when a process pauses longer than its lease; use fencing tokens (Distributed Locking).

Scaling path: 1x, 10x, 100x ​

ScaleTime and number concernAction
1x (one process)correctness: UTC storage, Equal, zonestests with a fake clock; go 1.23+ in go.mod
10x (many requests)time.Now and Format allocation in hot paths; time.After per requestAppendFormat, one timer per connection, benchmarks
100x (many services)skew, retry storms, tzdata drift between servicesjitter, deadlines as durations, one tzdata policy, monitor NTP
anytokens predicted from weak randomnesscrypto/rand everywhere secrets are created

Lab ​

Everything here runs on a laptop with Go 1.24 or later; no Docker. Outputs marked "(real)" were produced on the host while writing this page (Go 1.27.4, macOS arm64); anything else is labelled "expected, not run".

bash
cd docs/snippets/go/time-random-numbers/go
gofmt -l .            # no output
go vet ./...          # no output
go test -race -count=1 ./...   # ok for 10 packages (real)

1. Offsets around the Iranian DST change (real) ​

bash
go run ./lab
# Tehran 2021-07-01 12:00 -> offset +04:30, UTC 2021-07-01T07:30:00Z
# Tehran 2022-07-01 12:00 -> offset +04:30, UTC 2022-07-01T07:30:00Z
# Tehran 2023-07-01 12:00 -> offset +03:30, UTC 2023-07-01T08:30:00Z

2. AddDate versus Add across the New York spring jump (real) ​

bash
# AddDate(0,0,1): 2024-03-10T12:00:00-04:00
# Add(24h):       2024-03-10T13:00:00-04:00
# 02:30 gap -> 2024-03-10T01:30:00-05:00 exact: false

3. Parse errors and numbers (real) ​

bash
# parse error: parsing time "2025-03-09 14:05:07" as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T"
# parse error: parsing time "2025-02-30": day out of range
# 0.1+0.2 = 0.30000000000000004 equals 0.3: false
# ParseInt: strconv.ParseInt: parsing "128": value out of range
# 12.34 -> 1234 cents; split 1000 by 3: [334 333 333]
# PCG(1,2): 76 61 78 79 23
# next 09:00 after 2025-06-01T09:00:00+03:30 -> 2025-06-02T09:00:00+03:30

4. Timer reset on a 1.22 module versus a 1.24 module (expected, not run) ​

Copy the timers package into a module whose go.mod says go 1.22 and run TestResetDoesNotDeliverStaleValue; expected: it fails with stale tick received after Reset because the channel is buffered (cap(tm.C) == 1). With go 1.24 (the committed go.mod) it passes (real). GODEBUG=asynctimerchan=1 go test ./timers on the 1.24 module is expected to reproduce the old behaviour.

5. Benchmark (real, single run) ​

bash
go test -run xxx -bench . -benchmem ./bench
# BenchmarkNow-12                 36792697   27.92 ns/op    0 B/op   0 allocs/op
# BenchmarkSince-12              100000000   12.11 ns/op    0 B/op   0 allocs/op
# BenchmarkFormatRFC3339-12       53199152   22.24 ns/op   24 B/op   1 allocs/op
# BenchmarkParseRFC3339-12        69774706   16.68 ns/op    0 B/op   0 allocs/op
# BenchmarkAppendFormatRFC3339-12 74869170   16.05 ns/op    0 B/op   0 allocs/op

6. A container without tzdata (expected, not run) ​

Build the zones test into a FROM scratch image without the time/tzdata import: LoadLocation("Asia/Tehran") is expected to fail with unknown time zone Asia/Tehran. With the import, or go build -tags timetzdata, it succeeds and the binary is about 450 KB larger.

Common misconceptions ​

BeliefReality
time.Time is a Unix timestampIt is wall + monotonic readings + a location
a == b compares two timesIt compares fields; use Equal
The zero Time is the Unix epochIt is 0001-01-01 00:00:00 UTC
time.Parse uses my local zoneZone-less input is UTC; use ParseInLocation
YYYY-MM-DD works as a layoutLayouts use the reference date 2006-01-02
A day is 24 * time.HourDays are 23 or 25 hours on DST changes
Iran still has DSTNot since 2022 (tzdata 2022b)
I must drain a timer channel after StopNot on a go 1.23+ module
rand.Seed(time.Now().UnixNano()) is best practiceDead code since Go 1.20, a no-op since 1.24
math/rand/v2 is fine for tokensUse crypto/rand for secrets
ParseInt returns 0 on overflowIt returns the clamp and ErrRange
float64 is fine for pricesUse integers in minor units
time.Sleep can be cancelledWait on a timer and ctx.Done()
timestamp and timestamptz differ only by labeltimestamptz normalises to UTC; timestamp keeps whatever wall time you wrote

Cheat sheet ​

TopicWhat to remember
Elapsed timetime.Since(start) uses the monotonic reading
Same instanta.Equal(b), a.Compare(b); never ==
Unset timet.IsZero(); JSON omitzero (Go 1.24)
Durationint64 ns; time.Duration(n) * time.Second; no Day constant
LayoutReference 01/02 03:04:05PM '06 -0700; 2006-01-02T15:04:05Z07:00 is RFC3339
ParseParse gives UTC without zone text; ParseInLocation for local wall times
ZonesLoadLocation("Asia/Tehran"); embed with import _ "time/tzdata" in main
StorageUTC instants, timestamptz, RFC3339 in JSON, Unix ms in streams
DSTAddDate for wall days, Add for elapsed time; gaps and overlaps exist
TimerStop/Reset are stale-free on go 1.23+ modules; defer tk.Stop()
Waitingselect on timer.C and ctx.Done() instead of Sleep
TestsClock interface and a fake; testing/synctest in Go 1.25
Randommath/rand/v2 for general use, PCG/ChaCha8 for repeatable, crypto/rand for secrets
ParsingParseInt(s, base, bits); use errors.Is(err, strconv.ErrRange)
Moneyint64 minor units, split remainders explicitly

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a == b be false while a.Equal(b) is true? Important ​

Answer

Answer: == compares the wall and monotonic readings and the *Location pointer; Equal compares only the instant.

2 — What does time.Parse(time.DateTime, "2025-03-09 14:05:07") return as its location? Important ​

Answer

Answer: UTC. Use ParseInLocation to read the same text as a wall time in another zone.

3 — Which operations strip the monotonic reading? Good to know ​

Answer

Answer: In, UTC, Local, Round, Truncate, AddDate, and every serialisation or constructor (JSON, Parse, Date, Unix). Round(0) is the idiom.

4 — How do AddDate(0, 0, 1) and Add(24 * time.Hour) differ on 2024-03-10 in New York? Must-know ​

Answer

Answer: The first keeps 12:00 wall time (23 elapsed hours); the second advances 24 elapsed hours and lands on 13:00.

5 — What changed for Timer.Reset in Go 1.23, and when does it apply? Important ​

Answer

Answer: Timer channels are unbuffered, so no stale value is delivered after Reset or Stop; unreferenced timers are collectable. It applies when the main module's go line is 1.23 or later (and asynctimerchan is not 1).

6 — Why is time.Sleep wrong in a retry loop that must stop on shutdown? Must-know ​

Answer

Answer: It cannot be cancelled. Wait on a Timer and ctx.Done() in a select.

7 — When must you import time/tzdata? Good to know ​

Answer

Answer: When the binary may run where the OS has no zoneinfo (scratch or distroless images); import it in main, accepting about 450 KB.

8 — Which random package for a password-reset token, and why? Must-know ​

Answer

Answer: crypto/rand (for example rand.Text()); math/rand/v2 is not designed for secrets.

9 — What does strconv.ParseInt("128", 10, 8) return? Important ​

Answer

Answer: 127 (the clamp) and an error strconv.ParseInt: parsing "128": value out of range, matching strconv.ErrRange.

10 — How do you represent 12.34 in a database and in Go code? Must-know ​

Answer

Answer: As the integer 1234 of minor units plus a currency code; parse by splitting the string, never through float64.

11 — Why does a stale tzdata make a Tehran report wrong in 2023? Important ​

Answer

Answer: Iran stopped DST after 2022 (tzdata 2022b); older data still applies +04:30 in summer.

Glossary ​

TermMeaning
time.TimeInstant with wall reading, optional monotonic reading and a location
wall clockCalendar time; can jump by NTP or manual change
monotonic clockEver-increasing counter used for elapsed time, process-local
time.Durationint64 count of nanoseconds
Subt.Sub(u): duration between two times
Since / UntilNow().Sub(t) and t.Sub(Now()) using the monotonic reading
EqualSame-instant comparison
IsZeroTrue for 0001-01-01 00:00:00 UTC
layoutReference-date string describing a format
RFC33392006-01-02T15:04:05Z07:00, the internet profile of ISO 8601
RFC3339NanoRFC3339 with trimmed nanoseconds; does not sort lexically
DateTime constanttime.DateTime, the layout 2006-01-02 15:04:05
ParseInLocationParse zone-less text as wall time in a given location
LoadLocationLoad an IANA zone by name
time/tzdataPackage embedding the IANA database (+450 KB)
UTCCoordinated Universal Time, the storage zone
DSTDaylight saving time: clocks shifted seasonally
tzdataThe IANA time zone database
Asia/TehranIANA zone for Iran; +03:30, DST abolished after 2022
TimerOne-shot channel timer
TickerRepeating channel timer
Stop / ResetCancel and re-arm a timer; stale-free from Go 1.23
time.AfterChannel that receives once after a delay
time.AfterFuncRuns a function in its own goroutine after a delay
fake clockTest clock moved manually
clock interfaceSmall interface that returns "now"
cronTime-based job scheduling syntax
timestamptzPostgreSQL instant type stored as UTC
Unix epoch1970-01-01 00:00:00 UTC, the zero of Unix time
Jalali calendarPersian Solar Hijri calendar
math/randOriginal pseudo-random package
math/rand/v2Redesigned package: IntN, N, PCG, ChaCha8
rand.NGeneric random value in [0, n) for any integer type
ChaCha8Stream-cipher based generator, global default in v2
PCGPermuted congruential generator, 16 bytes of state
ShuffleIn-place random permutation with a swap function
seedInitial state that fixes a pseudo-random sequence
crypto/randCryptographically secure randomness from the OS
strconv.ParseIntText to integer with base and bit size
bit sizeWidth the parsed integer must fit
baseNumeral base 2 to 36, or 0 to detect by prefix
ParseFloatText to nearest float64 or float32
math/bigArbitrary-precision integers, rationals and floats
minor unitsSmallest currency unit as an integer, such as cents
FormatFloatFloat to text with format, precision and bit size
DateTimeImmutablePHP's immutable date-time class
CarbonLaravel's date library extending PHP DateTime
random_intPHP's cryptographically secure integer function

For PHP/Laravel developers ​

TaskPHP/LaravelGo
Current timenow() or Carbon::now()time.Now()
Immutable dateDateTimeImmutable, CarbonImmutabletime.Time is a value; every method returns a new one
ParseCarbon::parse($s) guesses the formattime.Parse(layout, s), explicit
Zone->setTimezone('Asia/Tehran')t.In(loc)
Add a day->addDay()AddDate(0, 0, 1)
Elapsed$a->diffInSeconds($b)b.Sub(a)
Tokensrandom_int, Str::random()crypto/rand
Seeded randommt_srand(42); mt_rand()rand.New(rand.NewPCG(a, b))
Jalalimorilog/jalaligo-persian-calendar
php
$when = new DateTimeImmutable('2025-06-01 09:00', new DateTimeZone('Asia/Tehran'));
$next = $when->modify('+1 day');           // same wall time tomorrow, like AddDate
$code = random_int(0, 999999);             // secure, like crypto/rand

Laravel's Eloquent casts created_at to Carbon (it extends DateTime); immutable_datetime casts return immutable instances. Go has no mutable date object at all, which removes a class of bugs where $date->addDay() changes a shared instance. Laravel's Carbon::parse accepts many formats and guesses; Go makes you write the layout, so a wrong format is an error at the boundary instead of a wrong date.

References ​

Fetchable pages were saved under the scratchpad sources/time-random-numbers/ folder; package documentation was read through go doc (Go 1.27.4) because pkg.go.dev returns HTTP 403 to non-browser clients.

Built by Morteza Negahi