Format Durations Human Readable

Break a Duration into hours, minutes, and seconds for human readable CLI output, since Debug prints machine units like 90061s.

RustCli Tooling

Code

rustsnippet
27 lines
use std::time::Duration;

// Duration 的 Debug 只会挑一个单位:90061s 这类输出对人不友好。
// 按 3600 与 60 拆出时分秒,拼成 25h 1m 1s 的习惯写法。
fn human_readable(d: Duration) -> String {
    let total = d.as_secs();
    let hours = total / 3600;
    let minutes = (total % 3600) / 60;
    let seconds = total % 60;
    match (hours, minutes, seconds) {
        (0, 0, s) => format!("{s}s"),
        (0, m, s) => format!("{m}m {s}s"),
        (h, m, s) => format!("{h}h {m}m {s}s"),
    }
}

fn main() {
    let samples = [
        Duration::from_secs(42),
        Duration::from_secs(7262),
        Duration::from_millis(500), // 亚秒部分按秒粒度截断
        Duration::from_secs(90061),
    ];
    for d in samples {
        println!("{:>10?} -> {}", d, human_readable(d));
    }
}

Reading the flow of control

Everything happens inside the functions human_readable and main.

for d in samples is the loop that carries the per-item work. Pattern matching via match forces each shape of the value to be handled.

What to watch for

  • No dependencies section needed; the standard library is the whole story.

Putting it to use

The head of the file is the signature: fn human_readable(d: Duration) -> String

Treat main as the orchestrator calling human_readable in a fixed order.

Core lines

match (hours, minutes, seconds) {
    (0, 0, s) => format!("{s}s"),
    (0, m, s) => format!("{m}m {s}s"),
    (h, m, s) => format!("{h}h {m}m {s}s"),
}

Interactive Tools for This Topic

FAQ

How do you run Format Durations Human Readable?
The file is self-contained: run it directly, no dependencies to install beforehand.