Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Time & randomness

Record wall-clock time for an event

Rust

SystemTime models wall time. UNIX_EPOCH conversion returns an error for a time earlier than the epoch.

Fragment

Use a compatible Result context. Human/time-zone formatting commonly uses a separate named time library.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let seconds = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)?.as_secs();

Measure elapsed time with a monotonic clock

Rust

Instant is intended for elapsed durations rather than civil timestamps.

Fragment

Instant is not a portable serialized timestamp.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let start = std::time::Instant::now();
work();
let elapsed = start.elapsed();

Choose a random value for ordinary simulation

Rust

The optional rand crate supplies distributions and general-purpose generators.

Fragment

Example uses rand 0.10. Declare that Cargo dependency; choose documented secure generation when security properties matter.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let die: i32 = rand::random_range(1..=6);

Represent durations and add them to times: Temporal.Duration, time.Duration, std::time::Duration, std::chrono

Rust

std::time::Duration is an unsigned span (u64 seconds plus nanoseconds) built with from_secs, from_millis or from_secs_f64, and read with as_secs, as_millis or as_secs_f64. It cannot be negative: plain subtraction panics on underflow, while checked_sub returns None and saturating_sub stops at zero. Instant + Duration gives a monotonic deadline, and SystemTime + Duration a wall-clock time.

Complete program

Complete program.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

fn main() {
    // Duration is an unsigned span: whole seconds (u64) plus nanoseconds. It cannot be negative.
    let timeout = Duration::from_secs(30);
    let ttl = Duration::from_secs(8 * 3600) + Duration::from_secs(30 * 60);
    let backoff = Duration::from_millis(250) * 3; // multiply by a u32

    assert_eq!(backoff, Duration::from_millis(750));
    assert_eq!(ttl.as_secs(), 30_600);
    assert_eq!(ttl.as_secs_f64() / 3600.0, 8.5);
    println!("{timeout:?} {ttl:?} {backoff:?}"); // Debug: 30s 30600s 750ms

    // Subtraction that would go below zero: `-` panics, checked_/saturating_ do not.
    let short = Duration::from_millis(100);
    assert_eq!(short.checked_sub(timeout), None);
    assert_eq!(short.saturating_sub(timeout), Duration::ZERO);
    assert_eq!(
        timeout.checked_sub(short),
        Some(Duration::from_millis(29_900))
    );

    // Elapsed time and deadlines use Instant (monotonic).
    let start = Instant::now();
    let deadline = start + timeout;
    assert!(Instant::now() < deadline);
    let elapsed = start.elapsed();
    assert!(elapsed < timeout);

    // Wall-clock arithmetic: SystemTime + Duration, duration_since returns a Result.
    let issued = UNIX_EPOCH + Duration::from_secs(1_794_128_400); // 2026-11-08T09:00:00Z
    let expires = issued + ttl;
    let span = expires.duration_since(issued).expect("expires is later");
    assert_eq!(span, ttl);
    assert!(SystemTime::now().duration_since(UNIX_EPOCH).is_ok());

    // Durations from config: try_from_secs_f64 rejects negative, NaN and overflow.
    assert!(Duration::try_from_secs_f64(-1.0).is_err());
    println!(
        "expires at {}s after the epoch",
        expires.duration_since(UNIX_EPOCH).unwrap().as_secs()
    );
}

In practice: take Duration in APIs, compare against an Instant deadline for timeouts, and parse human durations ("1h30m") with the humantime crate (2.4) or by hand. Debug formatting ({:?}) prints readable values such as 750ms.

from_secs_f64 panics on negative, NaN or overflowing input; try_from_secs_f64 (Rust 1.66+) returns an error instead.

SystemTime::duration_since returns Err when the clock moved backwards; Instant::duration_since saturates to zero.

Duration has no Display impl, only Debug; format the fields yourself for user-facing text.

Format and parse timestamps: Temporal.Instant, time.Parse layouts, jiff, std::chrono::parse

Rust

std has no calendar, formatter or parser for dates; jiff (0.2) is the modern crate for them, and chrono (0.4) the long-standing one. jiff::Timestamp is an instant: "…Z".parse::<Timestamp>() reads RFC 3339, applies any offset, and rejects an impossible date, a missing offset or a malformed field; to_string() writes RFC 3339 in UTC. as_second and from_second convert to and from Unix seconds, and strftime / strptime handle other layouts.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add jiff@0.2

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use jiff::Timestamp;

fn main() -> Result<(), jiff::Error> {
    // Timestamp is an instant. FromStr and Display use RFC 3339 / ISO 8601.
    let t: Timestamp = "2026-11-08T14:05:09Z".parse()?;
    assert_eq!(t.to_string(), "2026-11-08T14:05:09Z");
    assert_eq!(t.as_second(), 1_794_146_709); // Unix seconds, the simplest machine format
    assert_eq!(Timestamp::from_second(1_794_146_709)?, t);

    // An offset in the input is applied: the same instant.
    let with_offset: Timestamp = "2026-11-08T15:05:09+01:00".parse()?;
    assert_eq!(with_offset, t);
    let precise: Timestamp = "2026-11-08T14:05:09.123Z".parse()?;
    assert_eq!(precise.subsec_millisecond(), 123);

    // Impossible dates, missing offsets and malformed fields are errors, not guesses.
    for bad in ["2026-02-30T10:00:00Z", "2026-11-08T10:00:00", "2026-+1-08T14:05:09Z"] {
        assert!(bad.parse::<Timestamp>().is_err(), "{bad}");
    }

    // strftime / strptime for other layouts.
    println!("{}", t.strftime("%a, %d %b %Y %H:%M:%S %z")); // Sun, 08 Nov 2026 14:05:09 +0000
    let custom = Timestamp::strptime("%Y-%m-%d %H:%M:%S %z", "2026-11-08 15:05:09 +0100")?;
    assert_eq!(custom, t);

    // now() has sub-second precision; round it for logs.
    let now = Timestamp::now().round(jiff::Unit::Second)?;
    println!("now: {now}");
    Ok(())
}

In practice: exchange RFC 3339 strings or Unix seconds, parse with Timestamp, and keep the error instead of defaulting. With chrono the same calls are DateTime::parse_from_rfc3339 and to_rfc3339.

Built with jiff 0.2.40; chrono 0.4.45 is the current chrono. A Timestamp converts to and from std::time::SystemTime with From/TryFrom.

Unix seconds ignore leap seconds, as RFC 3339 timestamps from most systems do; jiff reads a :60 second as :59.

std only: SystemTime::now().duration_since(UNIX_EPOCH) gives Unix seconds, the simplest portable timestamp; anything with a calendar needs a crate.

Convert between UTC, local time and time zones: Temporal.ZonedDateTime, time.LoadLocation, jiff, zoned_time

Rust

std has no calendar and no time zones, so named zones come from a crate; jiff (0.2) is the usual choice. timestamp.in_tz("America/New_York")? gives a Zoned (an instant plus a zone and its DST rules), date(2026, 3, 9).at(9, 0, 0, 0).in_tz(...) builds a wall time in the zone, and .offset() reports the offset in force. checked_add(1.day()) is calendar arithmetic that keeps the wall-clock time across a DST change; checked_add(24.hours()) is exact time. A wall time in a DST gap is moved forward by default.

Complete program

Complete program. Reads the system zone database on Unix.

Before you use this

Not in the standard library: cargo add jiff@0.2

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use jiff::civil::date;
use jiff::tz::{self, TimeZone};
use jiff::{SignedDuration, Timestamp, ToSpan};

fn main() -> Result<(), jiff::Error> {
    // A Timestamp is an instant; in_tz attaches an IANA zone and its DST rules (a Zoned).
    let winter: Timestamp = "2026-01-15T17:00:00Z".parse()?;
    let summer: Timestamp = "2026-07-15T17:00:00Z".parse()?;
    let ny_winter = winter.in_tz("America/New_York")?;
    assert_eq!(ny_winter.offset(), tz::offset(-5));
    assert_eq!(summer.in_tz("America/New_York")?.offset(), tz::offset(-4)); // DST
    assert_eq!(winter.in_tz("Asia/Kolkata")?.hour(), 22); // +05:30, no DST
    println!("{ny_winter}"); // 2026-01-15T12:00:00-05:00[America/New_York]

    // Build a wall time in a zone: 09:00 in New York, whatever the offset is that day.
    let meeting = date(2026, 3, 9).at(9, 0, 0, 0).in_tz("America/New_York")?;
    assert_eq!(meeting.timestamp().to_string(), "2026-03-09T13:00:00Z"); // DST began 8 March

    // DST-safe "add one day": a calendar day keeps 09:00 local; 24 hours does not.
    let saturday = date(2026, 3, 7).at(9, 0, 0, 0).in_tz("America/New_York")?;
    let sunday = saturday.checked_add(1.day())?;
    assert_eq!(sunday.hour(), 9);
    assert_eq!(saturday.duration_until(&sunday), SignedDuration::from_hours(23));
    assert_eq!(saturday.checked_add(24.hours())?.hour(), 10);

    // 02:30 on 8 March does not exist there; the default (compatible) strategy moves it forward.
    let gap = date(2026, 3, 8).at(2, 30, 0, 0).in_tz("America/New_York")?;
    assert_eq!(gap.hour(), 3);

    // Unknown names are errors; TimeZone::system() is the local zone.
    assert!(TimeZone::get("Mars/Olympus").is_err());
    println!("local zone: {}", TimeZone::system().iana_name().unwrap_or("unknown"));
    Ok(())
}

In practice: store Timestamps (UTC) and the IANA zone name, convert with in_tz for display or calendar steps, and get the local zone from TimeZone::system(). With chrono (0.4), chrono-tz supplies the database: utc.with_timezone(&chrono_tz::America::New_York).

Built with jiff 0.2.40. It reads /usr/share/zoneinfo on Unix and bundles the database on Windows and WASM; the tzdb-bundle-always feature bundles it everywhere, for example in minimal containers.

Zoned::with().disambiguation(...) or tz.to_ambiguous_zoned(...) choose how a gap or overlap resolves, if the default (compatible) is not what you want.

chrono-tz embeds a snapshot of the database, so updating zone rules means updating the crate. A hard-coded offset is wrong for half the year in zones with DST.

Generate reproducible random numbers: seeded PRNGs, rand.NewPCG, StdRng, std::mt19937

Rust

std has no random number generator; the rand crate (0.10) is the standard choice. StdRng::seed_from_u64(seed) (the SeedableRng trait) gives a generator that repeats its sequence for the same seed, random_range(1..=6) and random() (the RngExt trait) draw uniform values (rand accepts a bias below 2^-48 by default; its unbiased feature removes it), and slice.shuffle(&mut rng) (SliceRandom) is a Fisher-Yates shuffle.

Complete program

Complete program. Set TEST_SEED to replay a different sequence.

Before you use this

Not in the standard library: cargo add rand

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use rand::{RngExt, SeedableRng};

fn main() {
    // Read the seed from the environment so a failing run can be replayed.
    let seed: u64 = std::env::var("TEST_SEED")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(42);

    // Same seed, same sequence.
    let mut a = StdRng::seed_from_u64(seed);
    let mut b = StdRng::seed_from_u64(seed);
    let rolls_a: Vec<u32> = (0..5).map(|_| a.random_range(1..=6)).collect();
    let rolls_b: Vec<u32> = (0..5).map(|_| b.random_range(1..=6)).collect();
    assert_eq!(rolls_a, rolls_b);

    let mut names = ["ann", "bo", "cy", "di"];
    names.shuffle(&mut StdRng::seed_from_u64(seed)); // Fisher-Yates
    let unit: f64 = a.random(); // [0, 1)
    println!("seed={seed} rolls={rolls_a:?} order={names:?} float={unit:.3}");
}

In practice: read the seed from a test parameter or environment variable, print it when a test fails, and pass &mut impl Rng into the code under test instead of calling rand::rng() inside it. StdRng's algorithm may change in a new rand release; for golden values that must survive upgrades, use a named algorithm such as rand::rngs::Xoshiro256PlusPlus or ChaCha8Rng.

Built with rand 0.10.3. rand 0.10 moved random_range, random and friends to the RngExt trait; code written for 0.9 imports Rng instead.

Values drawn through distributions (random_range, shuffle) can also change between rand minor releases; pin the version (Cargo.lock) when tests compare exact output. ChaCha8Rng needs the "chacha" feature.

Seeded generators are predictable by design: never use them for secrets.

Generate secure random tokens: crypto.getRandomValues, crypto/rand, getrandom, OS CSPRNGs

Rust

Stable std has no public secure random API (a std::random module is nightly-only), so it comes from crates. getrandom (0.4) is the low-level one: getrandom::fill(&mut buf)? fills a buffer from the OS generator, using the right system call on each platform (getrandom on Linux, getentropy on macOS, ProcessPrng on Windows). rand (0.10) builds on it: rand::rng() is a CSPRNG seeded from the OS, and random_range draws uniform integers (bias below 2^-48 unless rand’s unbiased feature is enabled).

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add getrandom rand

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use rand::RngExt;

fn main() -> Result<(), getrandom::Error> {
    // Raw bytes straight from the OS generator (getrandom, getentropy, ProcessPrng, ...).
    let mut key = [0u8; 32];
    getrandom::fill(&mut key)?;
    let token: String = key.iter().map(|b| format!("{b:02x}")).collect();
    assert_eq!(token.len(), 64); // 256 bits as hex

    // rand::rng() is a CSPRNG seeded from the OS; random_range is uniform up to a bias below 2^-48 (enable rand’s unbiased feature to remove it).
    let code: u32 = rand::rng().random_range(0..1_000_000);
    println!("token={}... code={code:06}", &token[..16]);
    Ok(())
}

In practice: make tokens from 32 random bytes encoded as hex or base64url, store only a hash of long-lived ones, and compare presented secrets with a constant-time function such as subtle::ConstantTimeEq.

Built with getrandom 0.4.3 and rand 0.10.3. Older code calls getrandom::getrandom(&mut bytes), the 0.2 name for fill.

rand::rngs::SysRng reads the OS generator on every call, for code that wants no user-space state at all.

std only, Unix: File::open("/dev/urandom")?.read_exact(&mut buf) reads the same OS generator, but fails in a chroot or sandbox without /dev and does not exist on Windows.