Nyx by Example

Date and Time

Nyx provides built-in time functions for the most common needs: Unix timestamps in seconds and milliseconds, a formatted current datetime string, and conversion from an epoch value back to a human-readable date. No import is required for these primitives.

Code

// 19: Date and time — timestamps, formatting, sleep
fn main() -> int {
    // Current Unix timestamp
    let now: int = time()
    print("Unix timestamp: " + int_to_string(now))

    // Millisecond precision
    let ms: int = time_ms()
    print("Milliseconds: " + int_to_string(ms))

    // Formatted datetime
    let dt: String = datetime_now()
    print("Current datetime: " + dt)

    // From epoch
    let formatted: String = datetime_from_epoch(now)
    print("From epoch: " + formatted)

    return 0
}

Output

Unix timestamp: 1744761600
Milliseconds: 1744761600123
Current datetime: 2026-04-15 12:00:00
From epoch: 2026-04-15 12:00:00

Explanation

time() returns the current Unix timestamp as an int — the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). This is the standard way to record event times, measure durations by subtracting two timestamps, or set expiry times for caches and tokens.

time_ms() returns the same value but with millisecond precision, useful for benchmarking short operations or generating monotonically increasing IDs. datetime_now() returns the local time formatted as a human-readable string in ISO-8601 style.

datetime_from_epoch(ts) converts any Unix timestamp back to the same human-readable format. This is handy when you store raw timestamps in a database or log file and want to display them later. For more advanced date arithmetic — adding days, parsing arbitrary formats, or working with time zones — see std/datetime.

← Previous Next →

Source: examples/by-example/19-datetime.nx