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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why time is harder than it looks | Why it exists |
| Where the rules come from | Where it comes from |
Wall clock versus monotonic clock, Since, Sub | time.Time |
== versus Equal, the zero time, IsZero | Comparing and the zero time |
time.Duration, ParseDuration, 5 * time.Second | Duration |
2006-01-02T15:04:05Z07:00 and the reference date | Layouts: Format and Parse |
parsing time ... cannot parse ... as ... | Parse errors |
LoadLocation, Local, FixedZone, time/tzdata | Time zones |
| Store UTC, show local | The UTC storage rule |
| 23-hour and 25-hour days, gaps, overlaps | DST traps |
| Asia/Tehran, Iran stopped DST in 2022 | tzdata updates and Iran |
NewTimer, Stop, Reset, Go 1.23 changes | Timer and Ticker |
time.After in a loop, AfterFunc | time.After and AfterFunc |
time.Sleep and cancelling it | Sleeping and contexts |
How expensive is time.Now | Measuring time |
Fake clock, clock interface, synctest | Clock abstraction for tests |
Cron, robfig/cron, daily jobs | Scheduling |
timestamptz, Unix epoch, JSON | Persistence of time |
| Persian (Jalali) calendar | Jalali calendar |
math/rand, math/rand/v2, seeds, rand.N, ChaCha8, PCG | Pseudo-random numbers |
Tokens, keys, crypto/rand | Secure randomness |
strconv.ParseInt, base, bit size | Parsing integers |
ParseFloat, 0.1 + 0.2, math/big | Floats and big numbers |
| Money, minor units | Money as integers |
FormatFloat, %g, math helpers | Formatting numbers |
| Which package for which job | Choosing |
| One process to many services | In architecture |
| Run it yourself | Lab |
Everything in one minute
| Thing | Plain words | Tiny example | Gotcha |
|---|---|---|---|
time.Now() | Current instant with wall and monotonic readings | start := time.Now() | Printing it shows m=+0.0123 |
time.Since(t) | Elapsed time, immune to wall-clock jumps | time.Since(start) | Use it for durations, never Now().Sub on parsed times |
t.Equal(u) | Same instant, any location | a.Equal(b) | a == b also compares location and monotonic reading |
t.IsZero() | Is this the zero Time | var t time.Time | Zero is year 1, not 1970 |
time.Duration | int64 nanoseconds | 90 * time.Second | time.Second * n with an int n does not compile |
| layout | A sample date that shows the shape | "2006-01-02" | YYYY-MM-DD is not a layout |
time.Parse | Text to Time; no zone in text means UTC | time.Parse(time.DateOnly, s) | Not the server's local zone |
ParseInLocation | Text with no zone, interpreted in a zone | ParseInLocation(l, s, loc) | The right call for user-entered wall times |
LoadLocation | Zone by IANA name | "Asia/Tehran" | Fails in scratch images without tzdata |
time/tzdata | Embeds the zone database, about 450 KB | import _ "time/tzdata" | Import it in main, not in libraries |
Timer | One future event on a channel | time.NewTimer(d) | Always Stop it or let Go 1.23 collect it |
Ticker | Repeated events | time.NewTicker(d) | d must be positive, drops ticks for slow readers |
time.AfterFunc | Run a function later in its own goroutine | AfterFunc(d, f) | Stop does not wait for f |
rand/v2 global | Fast, auto-seeded, ChaCha8 | rand.IntN(10) | Not for secrets |
crypto/rand | OS-backed secure bytes | rand.Read(b) | Slower, never seed it |
strconv.ParseInt | Text to integer with base and bit size | ParseInt(s, 10, 64) | Out of range returns the clamp and an error |
| money | Integers in minor units | 1234 cents | Never float64 for money |
| Go version | What changed for this page | Where |
|---|---|---|
| 1.15 | Ticker.Reset | Timer and Ticker |
| 1.9 | Transparent monotonic time inside every Time | time.Time |
| 1.17 | Time.UnixMilli, UnixMicro | Persistence |
| 1.20 | math/rand seeds itself; rand.Seed deprecated; time.DateTime, DateOnly, TimeOnly; Time.Compare (1.20) | Pseudo-random numbers, Layouts |
| 1.22 | math/rand/v2; ChaCha8 in the runtime; loop variable per iteration | Pseudo-random numbers |
| 1.23 | Timer channels unbuffered; unreferenced timers collectable; time.Tick collectable | Timer and Ticker |
| 1.24 | crypto/rand.Text; omitzero JSON tag; testing.B.Loop; rand.Seed is a no-op | Secure randomness, Persistence, Measuring |
| 1.25 | testing/synctest generally available | Fake clock |
| Mistake | Symptom | Section |
|---|---|---|
Comparing times with == | Equal-looking times differ | Comparing |
time.Parse for a local wall time | Off by the zone offset | Parse errors |
| Storing local time in the database | Reports shift twice a year | UTC rule |
Add(24 * time.Hour) for "tomorrow" | Wrong wall time after DST | DST |
time.After in a hot loop (module below go 1.23) | Memory grows until each timer fires | After |
Reset without draining (module below go 1.23) | Stale tick fires immediately | Timer |
math/rand for tokens | Predictable secrets | Secure randomness |
float64 for money | 0.30000000000000004 | Money |
Atoi result ignored | Silent zero | Parsing 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 choice | What you give up | What you get |
|---|---|---|
Time carries wall and monotonic readings | A simple == on times | Since and Sub survive clock changes |
Duration is an int64 of nanoseconds | Months and years as durations | No float rounding; arithmetic is integer |
| Layouts use a reference date | strftime-style %Y-%m-%d codes | One example doubles as documentation |
| Zones from the IANA database by name | Offsets such as +0330 as the model | History: Iran was +04:30 in summer 2022 and is +03:30 since |
| Timers on channels | Callbacks everywhere | select composes timeouts with cancellation |
math/rand/v2 and crypto/rand as separate packages | One "random" import | A visible decision between fast and unguessable |
strconv takes base and bit size | parseInt(s) convenience | No 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
- "A
time.Timeis a timestamp." It is an instant plus a display zone plus, fortime.Now()only, a monotonic reading. Two values for the same moment can be!=and stillEqual. - "
rand.Seed(time.Now().UnixNano())at the top ofmain." That was needed before Go 1.20; today it is dead code (a no-op since Go 1.24), and it never mademath/randsafe for secrets. - "
strconv.Atoiis enough for input." It parses base 10 only, intoint(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.
| Change | Release | Primary source |
|---|---|---|
math/rand auto-seeded; rand.Seed deprecated | Go 1.20 | go.dev/doc/go1.20 |
math/rand/v2 introduced; ChaCha8 and PCG; rand.N, IntN | Go 1.22 | go.dev/doc/go1.22, go.dev/blog/randv2 |
| Timer and Ticker channels unbuffered; unreferenced timers collectable | Go 1.23 | go.dev/doc/go1.23 |
rand.Seed calls become no-ops (randseednop=0 restores) | Go 1.24 | go.dev/doc/go1.24 |
testing/synctest stable | Go 1.25 | go.dev/doc/go1.25 |
| "Iran no longer observes DST after 2022" | tzdata 2022b, 2022-08-10 | data.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).
// 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 falseReal 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.
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 variableReal 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 timeReal 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).
// 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:
| Input | Layout | Error text |
|---|---|---|
2025-03-09 14:05:07 | time.RFC3339 | parsing time "2025-03-09 14:05:07" as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T" |
2025-02-30 | time.DateOnly | parsing time "2025-02-30": day out of range |
09/03/2025 | time.DateOnly | parsing time "09/03/2025" as "2006-01-02": cannot parse "09/03/2025" as "2006" |
Asia/Teheran | LoadLocation | unknown time zone Asia/Teheran |
"2025-05-01 08:30:00" | JSON into time.Time | the 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.DateTimeReal 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.
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 secondsReal 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).
// 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 instantReal 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):
| Question | Code | Result |
|---|---|---|
| Same wall time tomorrow | start.AddDate(0, 0, 1) | 2024-03-10T12:00:00-04:00 (23 elapsed hours) |
| 24 elapsed hours | start.Add(24 * time.Hour) | 2024-03-10T13:00:00-04:00 |
| A time inside the gap | time.Date(2024, 3, 10, 2, 30, 0, 0, ny) | 2024-03-10T01:30:00-05:00, not 02:30 |
| A time inside the overlap | time.Date(2024, 11, 3, 1, 30, 0, 0, ny) | first occurrence, EDT |
| Same 01:30 the second time | first.Add(time.Hour) | 01:30 EST |
| Daily job at 09:00 across fall back | daily.Next | 25 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.
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 source | How it is updated | Failure when stale |
|---|---|---|
Host OS (/usr/share/zoneinfo) | OS package updates (tzdata) | A long-lived VM with no updates |
| Container base image | Rebuild the image | Old images still running |
time/tzdata embedded | Rebuild with a newer Go release | A binary compiled before the change |
ZONEINFO pointing to a zip | You update the file | Forgotten file |
| PostgreSQL | Server's own tz files or OS | AT 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, silentlyReal 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:
| Call | Result |
|---|---|
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)==0Real 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).
// 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/opReal scenarios: latency histograms; slow-query logging; profiling a hot parser; choosing AppendFormat in a log encoder.
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 sleepingReal scenarios: token and session expiry, cache TTLs, rate-limiter refills, billing periods, "trial ends in 14 days".
// 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)}
}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 runReal scenarios: nightly reports, invoice generation on the first of the month (Jalali month start, see below), cache warming, certificate renewal checks, SLA reminders.
// 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.
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 formattingReal 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.
// 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:
| Piece | math/rand (v1) | math/rand/v2 |
|---|---|---|
| Global generator | auto-seeded since 1.20 | auto-seeded, ChaCha8, always |
| Seed function | rand.Seed (deprecated, no-op since 1.24) | none; use rand.New(src) |
| Ints in range | Intn(n), Int63n(n) | IntN(n), Int64N(n), Uint64N(n) |
| Generic helper | none | rand.N(max) for any integer type, including time.Duration |
| Algorithms | the Go 1 generator (about 5 KB of state) | PCG (16 bytes of state), ChaCha8 |
| Shuffle and permutation | Shuffle, Perm | Shuffle, Perm |
| Concurrency | global is safe; *Rand is not | global 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 lockReal 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.
// 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 paddedReal 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).
| Call | Result |
|---|---|
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 checkedReal 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.
// 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
}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.IntReal 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:
| Call | 1234.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) -> 2Real scenarios: log lines, CSV exports, human-readable sizes, percentage displays, rounding a computed fee.
Mechanics
Error and panic texts you will see Must-know
| Situation | Exact text |
|---|---|
| Layout mismatch | parsing time "2025-03-09 14:05:07" as "2006-01-02T15:04:05Z07:00": cannot parse " 14:05:07" as "T" |
| Impossible date | parsing time "2025-02-30": day out of range |
| Unknown zone | unknown time zone Asia/Teheran |
| Bad duration unit | time: unknown unit "d" in duration "1d" |
| Empty duration | time: invalid duration "" |
| Non-positive ticker | panic: non-positive interval for NewTicker |
| Duration times int | invalid operation: time.Second * n (mismatched types time.Duration and int) |
| Out of range int | strconv.ParseInt: parsing "128": value out of range |
| Not a number | strconv.Atoi: parsing "abc": invalid syntax |
| Context done during wait | context deadline exceeded or context canceled |
| Timer misuse in old modules | stale value received immediately after Reset (no message, just a wrong tick) |
Version gates and GODEBUG settings Must-know
| Setting | Effect | Default |
|---|---|---|
go 1.23 in go.mod | New timer semantics | on for modules at 1.23+ |
GODEBUG=asynctimerchan=1 | Back to buffered timer channels | off |
GODEBUG=randseednop=0 | rand.Seed works again | no-op since Go 1.24 |
GODEBUG=randautoseed=0 | Old fixed global seed for math/rand (Go 1.20) | auto-seeded |
ZONEINFO=/path/zoneinfo.zip | Where LoadLocation looks first | unset |
-tags timetzdata | Embed tzdata at build time | not embedded |
TZ=Asia/Tehran | Sets time.Local for the process | system 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
| Problem | Solution | How | Cost or limit |
|---|---|---|---|
| Elapsed time wrong after clock change | time.Since | monotonic reading | Not valid across processes or restarts |
| Same instant compares unequal | Equal or Compare | instant-only comparison | None |
| Zone-less text off by hours | ParseInLocation | pass the user's *Location | Needs a zone per user |
LoadLocation fails in containers | import _ "time/tzdata" | embedded database | +450 KB, update on Go upgrade |
| Wrong daily schedule on DST days | compute with time.Date in the zone | rule, not interval | Gap times need a policy |
| Hung sleep on shutdown | select on timer and ctx.Done() | helper Sleep(ctx, d) | None |
Stale ticks after Reset | go.mod at 1.23 or later | unbuffered channel | Old modules keep the old behaviour |
| Timers in tests | Clock interface, synctest | fake time | Fakes must implement every call you use |
| Predictable tokens | crypto/rand | OS entropy | Slower than math/rand |
| Unrepeatable simulation | rand.New(rand.NewPCG(a, b)) | explicit seeds | Not safe for concurrent use |
| Silent overflow on parse | ParseInt(s, 10, 32) | explicit width | Handle ErrRange |
| Float money | integers in minor units | ParseMinor | Currency 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 goal | Technique |
|---|---|
| Expiry boundary | Fake.Advance to one tick before and exactly at the deadline |
| DST behaviour | time.Date in America/New_York, assert offsets, not just hours |
| Parse errors | assert the exact error text only for stable cases; prefer errors.As for *time.ParseError |
| Random behaviour | seed rand.NewPCG; assert ranges for global generators |
| Timers | short real durations with generous margins, or synctest |
| tzdata drift | pin expected offsets for known dates; run tests with -tags timetzdata in CI |
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Elapsed time in one process | time.Since(start) | Duration.Round for logs | Monotonic reading |
| Time shown to a person | t.In(userLoc).Format(...) | cache *Location per user | Zone is a display concern |
| Timestamp in an API | RFC3339 in UTC | omitzero for optional times | Unambiguous, sortable if fixed width |
| Timestamp in PostgreSQL | timestamptz | microsecond truncation | Stored as UTC |
| Daily/weekly schedule | zone plus wall rule | cron library with CRON_TZ | DST and rule changes |
| One-shot delay | NewTimer with Stop | select with ctx.Done() | Cancellation |
| Periodic work | NewTicker | defer tk.Stop() | Releases the ticker |
| Deadline in a call chain | context.WithTimeout | check ctx.Err() | Propagates across layers |
| Shuffle, jitter, sampling | math/rand/v2 | rand.N for durations | Fast, no seeding |
| Reproducible random test data | rand.New(rand.NewPCG(a, b)) | log the seeds | Replay failures |
| Secrets and tokens | crypto/rand | rand.Text() | Unguessable |
| Parse user integers | ParseInt(s, 10, bits) | errors.Is on the error | Width and failure are explicit |
| Money | int64 minor units | currency code column | Exact |
| Huge exact numbers | math/big | avoid in hot loops | Allocation |
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 sequenceEach 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
| Scale | Time and number concern | Action |
|---|---|---|
| 1x (one process) | correctness: UTC storage, Equal, zones | tests with a fake clock; go 1.23+ in go.mod |
| 10x (many requests) | time.Now and Format allocation in hot paths; time.After per request | AppendFormat, one timer per connection, benchmarks |
| 100x (many services) | skew, retry storms, tzdata drift between services | jitter, deadlines as durations, one tzdata policy, monitor NTP |
| any | tokens predicted from weak randomness | crypto/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".
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)
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:00Z2. AddDate versus Add across the New York spring jump (real)
# 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: false3. Parse errors and numbers (real)
# 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:304. 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)
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/op6. 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
| Belief | Reality |
|---|---|
time.Time is a Unix timestamp | It is wall + monotonic readings + a location |
a == b compares two times | It compares fields; use Equal |
The zero Time is the Unix epoch | It is 0001-01-01 00:00:00 UTC |
time.Parse uses my local zone | Zone-less input is UTC; use ParseInLocation |
YYYY-MM-DD works as a layout | Layouts use the reference date 2006-01-02 |
A day is 24 * time.Hour | Days are 23 or 25 hours on DST changes |
| Iran still has DST | Not since 2022 (tzdata 2022b) |
I must drain a timer channel after Stop | Not on a go 1.23+ module |
rand.Seed(time.Now().UnixNano()) is best practice | Dead code since Go 1.20, a no-op since 1.24 |
math/rand/v2 is fine for tokens | Use crypto/rand for secrets |
ParseInt returns 0 on overflow | It returns the clamp and ErrRange |
float64 is fine for prices | Use integers in minor units |
time.Sleep can be cancelled | Wait on a timer and ctx.Done() |
timestamp and timestamptz differ only by label | timestamptz normalises to UTC; timestamp keeps whatever wall time you wrote |
Cheat sheet
| Topic | What to remember |
|---|---|
| Elapsed time | time.Since(start) uses the monotonic reading |
| Same instant | a.Equal(b), a.Compare(b); never == |
| Unset time | t.IsZero(); JSON omitzero (Go 1.24) |
| Duration | int64 ns; time.Duration(n) * time.Second; no Day constant |
| Layout | Reference 01/02 03:04:05PM '06 -0700; 2006-01-02T15:04:05Z07:00 is RFC3339 |
| Parse | Parse gives UTC without zone text; ParseInLocation for local wall times |
| Zones | LoadLocation("Asia/Tehran"); embed with import _ "time/tzdata" in main |
| Storage | UTC instants, timestamptz, RFC3339 in JSON, Unix ms in streams |
| DST | AddDate for wall days, Add for elapsed time; gaps and overlaps exist |
| Timer | Stop/Reset are stale-free on go 1.23+ modules; defer tk.Stop() |
| Waiting | select on timer.C and ctx.Done() instead of Sleep |
| Tests | Clock interface and a fake; testing/synctest in Go 1.25 |
| Random | math/rand/v2 for general use, PCG/ChaCha8 for repeatable, crypto/rand for secrets |
| Parsing | ParseInt(s, base, bits); use errors.Is(err, strconv.ErrRange) |
| Money | int64 minor units, split remainders explicitly |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
time.Time | Instant with wall reading, optional monotonic reading and a location |
| wall clock | Calendar time; can jump by NTP or manual change |
| monotonic clock | Ever-increasing counter used for elapsed time, process-local |
time.Duration | int64 count of nanoseconds |
Sub | t.Sub(u): duration between two times |
Since / Until | Now().Sub(t) and t.Sub(Now()) using the monotonic reading |
Equal | Same-instant comparison |
IsZero | True for 0001-01-01 00:00:00 UTC |
| layout | Reference-date string describing a format |
| RFC3339 | 2006-01-02T15:04:05Z07:00, the internet profile of ISO 8601 |
| RFC3339Nano | RFC3339 with trimmed nanoseconds; does not sort lexically |
| DateTime constant | time.DateTime, the layout 2006-01-02 15:04:05 |
ParseInLocation | Parse zone-less text as wall time in a given location |
LoadLocation | Load an IANA zone by name |
time/tzdata | Package embedding the IANA database (+450 KB) |
| UTC | Coordinated Universal Time, the storage zone |
| DST | Daylight saving time: clocks shifted seasonally |
| tzdata | The IANA time zone database |
| Asia/Tehran | IANA zone for Iran; +03:30, DST abolished after 2022 |
Timer | One-shot channel timer |
Ticker | Repeating channel timer |
Stop / Reset | Cancel and re-arm a timer; stale-free from Go 1.23 |
time.After | Channel that receives once after a delay |
time.AfterFunc | Runs a function in its own goroutine after a delay |
| fake clock | Test clock moved manually |
| clock interface | Small interface that returns "now" |
| cron | Time-based job scheduling syntax |
timestamptz | PostgreSQL instant type stored as UTC |
| Unix epoch | 1970-01-01 00:00:00 UTC, the zero of Unix time |
| Jalali calendar | Persian Solar Hijri calendar |
math/rand | Original pseudo-random package |
math/rand/v2 | Redesigned package: IntN, N, PCG, ChaCha8 |
rand.N | Generic random value in [0, n) for any integer type |
| ChaCha8 | Stream-cipher based generator, global default in v2 |
| PCG | Permuted congruential generator, 16 bytes of state |
Shuffle | In-place random permutation with a swap function |
| seed | Initial state that fixes a pseudo-random sequence |
crypto/rand | Cryptographically secure randomness from the OS |
strconv.ParseInt | Text to integer with base and bit size |
| bit size | Width the parsed integer must fit |
| base | Numeral base 2 to 36, or 0 to detect by prefix |
ParseFloat | Text to nearest float64 or float32 |
math/big | Arbitrary-precision integers, rationals and floats |
| minor units | Smallest currency unit as an integer, such as cents |
FormatFloat | Float to text with format, precision and bit size |
| DateTimeImmutable | PHP's immutable date-time class |
| Carbon | Laravel's date library extending PHP DateTime |
random_int | PHP's cryptographically secure integer function |
For PHP/Laravel developers
| Task | PHP/Laravel | Go |
|---|---|---|
| Current time | now() or Carbon::now() | time.Now() |
| Immutable date | DateTimeImmutable, CarbonImmutable | time.Time is a value; every method returns a new one |
| Parse | Carbon::parse($s) guesses the format | time.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) |
| Tokens | random_int, Str::random() | crypto/rand |
| Seeded random | mt_srand(42); mt_rand() | rand.New(rand.NewPCG(a, b)) |
| Jalali | morilog/jalali | go-persian-calendar |
$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/randLaravel'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.
- Go standard library, package
time(source and documentation): go.dev/src/time/time.go, go.dev/src/time/format.go, go.dev/src/time/sleep.go - Go standard library,
math/rand/v2source: go.dev/src/math/rand/v2/rand.go;crypto/rand: go.dev/src/crypto/rand/rand.go - Go blog, "Evolving the Go Standard Library with math/rand/v2": go.dev/blog/randv2
- Go blog, "Secure Randomness in Go 1.22": go.dev/blog/chacha8rand
- Go 1.9 release notes (transparent monotonic time): go.dev/doc/go1.9
- Go 1.20 release notes (rand auto-seed): go.dev/doc/go1.20
- Go 1.22 release notes (
math/rand/v2): go.dev/doc/go1.22 - Go 1.23 release notes (timer changes): go.dev/doc/go1.23
- Go 1.24 release notes (
omitzero,B.Loop,rand.Seedno-op): go.dev/doc/go1.24 - Go 1.25 release notes (
testing/synctest): go.dev/doc/go1.25 - The Go Programming Language Specification: go.dev/ref/spec
- Effective Go: go.dev/doc/effective_go
- Go FAQ: go.dev/doc/faq
- Go Code Review Comments: go.dev/wiki/CodeReviewComments
- IANA Time Zone Database: iana.org/time-zones; release notes: data.iana.org/time-zones/tzdb/NEWS (release 2022b, Iran)
- PostgreSQL manual, date/time types: postgresql.org/docs/current/datatype-datetime.html
robfig/cron: github.com/robfig/crongo-persian-calendar: github.com/yaa110/go-persian-calendar;morilog/jalali: github.com/morilog/jalali- PHP manual,
DateTimeImmutable: php.net/manual/en/class.datetimeimmutable.php;random_int: php.net/manual/en/function.random-int.php - Laravel 13 Eloquent mutators and casting: laravel.com/docs/13.x/eloquent-mutators
- Carbon: carbon.nesbot.com