Format Durations Human Readable
Break a Duration into hours, minutes, and seconds for human readable CLI output, since Debug prints machine units like 90061s.
Code
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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.
FAQ
- How do you run Format Durations Human Readable?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.