Docs/Building applications

Dates & time

Work with calendar dates, format them, and measure how long something took.

On this page

valk.time provides the current time, a monotonic clock for measuring durations, and DateTime for calendar dates.

Work with a UTC date#

Valk
use valk.time

fn main() {
    let date = time.DateTime.new(2026, 1, 15, 9, 30, 0, 0) ! {
        println("Invalid date")
        return
    }
    let tomorrow = date.add_days(1) ! {
        println("Date is outside the supported range")
        return
    }
    println(date.format("Y-m-d"))     // 2026-01-15
    println(tomorrow.format("Y-m-d")) // 2026-01-16
}

DateTime uses UTC. add_* and with_* methods return a new date; methods beginning with modify_ change the existing object. Invalid dates produce an error. DateTime.now() returns the current time.

Format and parse#

Valk
use valk.time

fn main() {
    let date = time.DateTime.from_format("Y-m-d H:i", "2026-03-01 14:30") ! {
        println("Invalid date text")
        return
    }
    println(date.format("d/m/Y H:i")) // 01/03/2026 14:30
    println(date.to_iso8601())        // 2026-03-01T14:30:00Z
}

The format tokens are Y (year), m (month), d (day), H (hour), i (minute), s (second), v (milliseconds) and u (microseconds). from_format reads text with the same tokens and fails when the text does not match. to_iso8601 produces the common machine-readable form, and unix_seconds() gives the Unix timestamp.

Measure elapsed time#

Valk
use valk.time

fn main() {
    let start = time.mono_ms()
    time.sleep_ms(20)
    let elapsed = time.mono_ms() - start
    println(elapsed >= 20) // true
}

time.mono_ms() is a monotonic clock: it only moves forward, even when the system clock is adjusted, so it is the right choice for durations. time.unix_ms() returns wall-clock time as milliseconds since 1970. time.sleep_ms pauses the current coroutine and lets other coroutines run.