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

C++

system_clock represents civil wall time; duration units must be explicit when exchanging a numeric timestamp.

Fragment

Include <chrono>. For C++20+ system_clock this epoch is Unix time; this example emits seconds, not milliseconds.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>

auto now = std::chrono::system_clock::now();
auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
    now.time_since_epoch()).count();

Measure elapsed time with a monotonic clock

C++

steady_clock is monotonic. Express the resulting duration in a chosen unit.

Fragment

Include <chrono>. work is the application operation being measured.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>

auto start = std::chrono::steady_clock::now();
work();
auto elapsed = std::chrono::steady_clock::now() - start;
auto milliseconds = std::chrono::duration<double, std::milli>(elapsed).count();

Choose a random value for ordinary simulation

C++

A distribution maps an engine’s output to the requested range. mt19937 is a pseudorandom simulation engine, not a cryptographic generator.

Fragment

Include <random>. Keep/reuse the engine instead of reseeding per generated value; a fixed seed enables repeatable simulations.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <random>

std::mt19937 generator(std::random_device{}());
std::uniform_int_distribution<int> die(1, 6);
auto value = die(generator);

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

C++

std::chrono::duration<Rep, Period> is a count with a compile-time unit, and the chrono literals (30s, 250ms, 8h) make values self-describing. Conversions that lose nothing are implicit (seconds to milliseconds); lossy ones need duration_cast (truncates toward zero), floor, ceil or round. Mixed arithmetic yields the finer common type, so 8h + 30min is a minutes value. C++20 adds hh_mm_ss for splitting and std::format support ("{}" prints 30s).

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <chrono>
#include <print>

using namespace std::chrono;
using namespace std::chrono_literals; // 30s, 250ms, 8h, 1.5s ...

int main() {
    // A duration is a count plus a unit (a std::ratio) checked at compile time.
    seconds timeout = 30s;
    auto ttl = 8h + 30min;           // the common type: minutes
    milliseconds backoff = 3 * 250ms;
    std::println("{} {} {}", timeout, ttl, backoff); // 30s 510min 750ms

    // Lossless conversions are implicit; lossy ones need duration_cast (truncates toward zero),
    // floor, ceil or round.
    milliseconds as_ms = timeout;
    assert(as_ms.count() == 30'000);
    assert(duration_cast<seconds>(1999ms) == 1s);
    assert(round<seconds>(1500ms) == 2s); // ties to even: 2.5s would round to 2s
    assert(floor<seconds>(-1500ms) == -2s); // durations are signed

    // Floating-point counts for ratios and display.
    duration<double, std::ratio<3600>> hours_f = ttl;
    assert(hours_f.count() == 8.5);

    // Split into fields for display.
    hh_mm_ss parts{duration_cast<seconds>(ttl + 15s)};
    std::println("{}h {}m {}s", parts.hours().count(), parts.minutes().count(), parts.seconds().count());

    // Time points: add a duration to sys_time (wall clock) or steady_clock (elapsed time).
    sys_seconds issued = sys_days{2026y / November / 8} + 9h;
    auto expires = issued + ttl;
    std::println("{:%FT%TZ}", expires); // 2026-11-08T17:30:00Z

    auto start = steady_clock::now();
    auto deadline = start + timeout;
    assert(steady_clock::now() < deadline);
}

In practice: take std::chrono::duration in APIs (or a template on it) instead of an int with a unit suffix, use steady_clock for deadlines, and convert to an explicit unit only at I/O boundaries.

round rounds halfway cases to even (2.5s becomes 2s); floor and ceil exist since C++17.

Counts are signed by default; a duration<unsigned> mixed with signed durations can wrap.

Use duration<double> for fractional results instead of dividing count() values yourself.

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

C++

C++20 <chrono> both formats and parses. std::format("{:%FT%TZ}", t) on a sys_seconds writes 2026-11-08T14:05:09Z (%F is the date, %T the time), and in >> std::chrono::parse(format, tp) reads the same specifiers from a stream: %Ez reads a +hh:mm offset and subtracts it, and an impossible date such as 30 February sets failbit instead of rolling over. The precision of the time_point decides what parse accepts: sys_seconds rejects a fraction, sys_time<milliseconds> reads one.

Complete program

Complete program. Needs a standard library with std::chrono::parse: libstdc++ 14+ (GCC 14) or MSVC 2019 16.10+. libc++ (Clang on macOS, and LLVM 22) does not have it yet.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <chrono>
#include <format>
#include <optional>
#include <print>
#include <sstream>
#include <string>

using namespace std::chrono;

// Parse an RFC 3339 timestamp with a Z or +hh:mm offset into UTC seconds.
// %Ez reads the offset and parse subtracts it; an impossible date sets failbit.
std::optional<sys_seconds> parse_rfc3339(const std::string& text) {
    std::istringstream in(text);
    sys_seconds t;
    if (text.ends_with('Z')) in >> parse("%FT%TZ", t);
    else in >> parse("%FT%T%Ez", t);
    if (in.fail() || in.peek() != std::char_traits<char>::eof()) return std::nullopt;
    return t;
}

int main() {
    // Formatting: std::format with chrono specifiers. %F is the date, %T the time.
    sys_seconds t = sys_days{2026y / November / 8} + 14h + 5min + 9s;
    assert(std::format("{:%FT%TZ}", t) == "2026-11-08T14:05:09Z");
    std::println("{:%a, %d %b %Y} | unix {}", t, t.time_since_epoch().count());

    // now() has sub-second precision; floor it first or %T prints the fraction.
    std::println("{:%FT%TZ}", floor<milliseconds>(system_clock::now()));

    assert(parse_rfc3339("2026-11-08T14:05:09Z") == t);
    assert(parse_rfc3339("2026-11-08T15:05:09+01:00") == t); // offset applied
    assert(!parse_rfc3339("2026-02-30T10:00:00Z"));          // no such date
    assert(!parse_rfc3339("2026-11-08T10:00:00"));           // no offset
}

In practice: floor system_clock::now() to seconds or milliseconds before formatting, parse into the precision your data has, and check in.fail() plus the end of input. Formatting is in every current standard library; for parse, see the notes.

Checked with GCC 14.4 (libstdc++). With libc++ the same file fails with "use of undeclared identifier 'parse'"; the std::format half works there. Howard Hinnant's date library (the reference implementation of C++20 chrono) provides date::parse with the same specifiers for those toolchains.

Without parse: check the fixed shape YYYY-MM-DDTHH:MM:SSZ, read the fields with std::from_chars, and validate the date with year_month_day::ok() before building sys_days{date} + hours{h} + ….

Formatting system_clock::now() directly prints the clock's fraction after %T; floor<seconds>(…) first for whole seconds. %Z on a sys_time prints UTC, so write a literal Z for RFC 3339.

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

C++

C++20 <chrono> includes the IANA time zone database. zoned_time pairs a sys_time (UTC) with a zone found by name through locate_zone; get_info().offset is the offset in force, and std::format prints it with %Z and %z. Built from a local_time, zoned_time resolves a wall time in the zone; a time in a DST gap throws nonexistent_local_time (an overlap throws ambiguous_local_time) unless you pass choose::earliest or choose::latest. Adding days{1} to get_local_time() and resolving again is the DST-safe "same time tomorrow"; if that wall time falls in a gap or overlap, the constructor throws too, so pass choose::earliest or choose::latest when that can happen.

Complete program

Complete program. Needs a standard library with the C++20 time zone database: libstdc++ 14+ (GCC 14) or MSVC 2019 16.10+. Clang with libc++ (macOS) does not provide it.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <chrono>
#include <format>
#include <print>
#include <stdexcept>

using namespace std::chrono;

int main() {
    // Keep instants in UTC (sys_time); a zoned_time pairs one with an IANA zone.
    sys_seconds winter = sys_days{2026y / January / 15} + 17h;
    sys_seconds summer = sys_days{2026y / July / 15} + 17h;
    zoned_time ny_winter{"America/New_York", winter};
    zoned_time ny_summer{"America/New_York", summer};
    assert(ny_winter.get_info().offset == -5h);
    assert(ny_summer.get_info().offset == -4h); // DST
    std::println("{:%F %H:%M %Z (%z)}", ny_winter); // 2026-01-15 12:00 EST (-0500)

    // Build a wall time in a zone: 09:00 in New York, whatever the offset is that day.
    zoned_time meeting{"America/New_York", local_days{2026y / March / 9} + 9h};
    assert(meeting.get_sys_time() == sys_days{2026y / March / 9} + 13h); // DST began 8 March

    // DST-safe "add one day": add to the local time, then resolve it in the zone again.
    // If the new local time falls in a gap or overlap this throws; pass choose (below).
    zoned_time saturday{"America/New_York", local_days{2026y / March / 7} + 9h};
    zoned_time sunday{saturday.get_time_zone(), saturday.get_local_time() + days{1}};
    assert(sunday.get_sys_time() - saturday.get_sys_time() == 23h); // the day was 23 hours
    zoned_time plus_24h{saturday.get_time_zone(), saturday.get_sys_time() + 24h};
    std::println("{:%F %H:%M %Z} | +24h: {:%H:%M}", sunday, plus_24h); // 09:00 vs 10:00

    // A wall time in the DST gap (02:30 on 8 March) throws unless you choose an offset.
    auto gap = local_days{2026y / March / 8} + 2h + 30min;
    try {
        zoned_time bad{"America/New_York", gap};
        assert(false);
    } catch (const nonexistent_local_time&) {
    }
    zoned_time moved{"America/New_York", gap, choose::latest};
    std::println("gap -> {:%H:%M %Z}", moved); // 03:00 EDT

    // Unknown zone names throw std::runtime_error; current_zone() is the local zone.
    try {
        (void)locate_zone("Mars/Olympus");
        assert(false);
    } catch (const std::runtime_error&) {
    }
    std::println("local zone: {}", current_zone()->name());
}

In practice: keep instants as sys_time, store the zone name, and convert with zoned_time only for display or calendar steps. current_zone() is the local zone.

Checked with GCC 14.4 (libstdc++). libc++ has only an experimental tzdb, behind -fexperimental-library and a build option that Apple's and Homebrew's builds leave off, so there "unknown type name 'zoned_time'" is the result. Howard Hinnant's date/tz library offers the same API as date::zoned_time.

POSIX fallback without a tzdb: setenv("TZ", "America/New_York", 1); tzset(); then localtime_r and strftime. setenv changes process-wide state and races with other threads calling localtime, so do it once at startup.

libstdc++ reads tzdata.zi from the system zoneinfo directory, or a copy built into the library; MSVC uses the ICU data that ships with Windows 10 1903 and later.

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

C++

<random> separates engines from distributions. Engines such as std::mt19937 are fully specified, so the same seed gives the same raw numbers on every implementation (the standard even fixes its 10000th value). Distributions are not: uniform_int_distribution, normal_distribution and std::shuffle may produce different values on libstdc++, libc++ and MSVC for the same engine state.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <array>
#include <cassert>
#include <cstdint>
#include <print>
#include <random>
#include <vector>

int main() {
    // Engines are fully specified by the standard: mt19937 with a given seed produces
    // the same raw numbers on every implementation.
    constexpr std::uint32_t seed = 42;
    std::mt19937 a(seed), b(seed);
    assert(a() == b());

    std::mt19937 reference(5489u); // the default seed
    reference.discard(9999);
    assert(reference() == 4123659995u); // the standard's required 10000th value

    // Distributions are NOT specified bit-for-bit: uniform_int_distribution, normal_distribution,
    // shuffle and friends may give different values on libstdc++, libc++ and MSVC.
    std::mt19937 engine(seed);
    std::uniform_int_distribution<int> die(1, 6);
    std::vector<int> rolls;
    for (int i = 0; i < 5; ++i) rolls.push_back(die(engine));

    std::mt19937 replay(seed);
    std::uniform_int_distribution<int> die2(1, 6);
    for (int roll : rolls) assert(die2(replay) == roll); // repeatable on the same library

    // Cross-platform golden values: derive from raw engine output yourself.
    std::mt19937 portable(seed);
    std::array<int, 5> portable_rolls{};
    for (int& r : portable_rolls) r = static_cast<int>(portable() % 6) + 1; // slight bias; fine for tests

    std::println("rolls={} portable={}", rolls, portable_rolls);
}

In practice: seed an engine explicitly for tests and reuse it; expect exact distribution output to be repeatable only with the same standard library. For golden files shared across platforms, derive values from raw engine output yourself or use a library with specified distributions.

Seeding mt19937 with one 32-bit value reaches only 2^32 of its states; that is fine for reproducible tests.

Construct the engine once and pass it by reference; a copy continues the same sequence independently, which causes repeated values.

Never use rand()/srand(): the algorithm and range (RAND_MAX) vary by platform.

Printing a std::vector or std::array with std::println needs range formatting (C++23): GCC 15+ (libstdc++) or libc++ 17+. On GCC 14, print the elements in a loop.

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

C++

The standard library has no generator guaranteed to be secure. std::random_device is meant to be non-deterministic, and is on current libstdc++, libc++ and MSVC, but the standard allows a deterministic fallback (old MinGW really did this), and entropy() is not a reliable way to tell. For secrets, call the OS: arc4random_buf on macOS and the BSDs (and glibc 2.36+), getrandom on Linux, BCryptGenRandom on Windows.

Complete program

Complete program (macOS, FreeBSD, OpenBSD or Linux).

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <array>
#include <cassert>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <format>
#include <print>
#include <random>
#include <string>
#include <system_error>

#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#include <stdlib.h> // arc4random_buf
#elif defined(__linux__)
#include <sys/random.h> // getrandom
#endif

// The standard library has no guaranteed-secure generator. std::random_device is meant to be
// non-deterministic, but the standard allows a deterministic fallback, and entropy() is not
// reliable. For secrets, call the OS: arc4random_buf, getrandom, or BCryptGenRandom on Windows.
void secure_fill(void* buffer, std::size_t size) {
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
    arc4random_buf(buffer, size); // cannot fail
#elif defined(__linux__)
    auto* bytes = static_cast<unsigned char*>(buffer);
    while (size > 0) {
        ssize_t n = getrandom(bytes, size, 0);
        if (n < 0) {
            if (errno == EINTR) continue; // interrupted by a signal: try again
            throw std::system_error(errno, std::generic_category(), "getrandom");
        }
        bytes += n;
        size -= static_cast<std::size_t>(n);
    }
#else
#error "add the platform CSPRNG (BCryptGenRandom on Windows)"
#endif
}

template <std::size_t N>
std::string hex_token() {
    std::array<unsigned char, N> bytes;
    secure_fill(bytes.data(), bytes.size());
    std::string out;
    for (unsigned char b : bytes) out += std::format("{:02x}", b);
    return out;
}

int main() {
    auto token = hex_token<32>(); // 256 bits
    assert(token.size() == 64);

    std::array<std::uint8_t, 16> a{}, b{};
    secure_fill(a.data(), a.size());
    secure_fill(b.data(), b.size());
    assert(a != b);

    // random_device is fine for seeding a simulation engine, not as a key source by contract.
    std::random_device device;
    std::mt19937 simulation(device());
    std::uniform_int_distribution<int> die(1, 6);
    std::println("token={}... die={}", token.substr(0, 16), die(simulation));
}

In practice: wrap the OS call in one function, use std::random_device only to seed simulation engines, and use OpenSSL's RAND_bytes or libsodium's randombytes_buf if the project already depends on them.

std::mt19937 seeded from random_device is predictable once someone sees 624 outputs; never use it for tokens.

getrandom(2) may return fewer bytes than asked for requests over 256 bytes, or fail with EINTR; loop as shown.

OpenSSL 3 RAND_bytes and libsodium randombytes_buf are good choices when already linked.