← 中文资源

简体中文版本

把 Duration 格式化成人可读时长

Duration 的 Debug 输出 90061s 这类机器单位:按 3600 与 60 拆出时分秒后拼装,CLI 展示 25h 1m 1s 才符合人的阅读习惯。

阅读英文原文

实现说明

全部逻辑都在函数 human_readable、main中。 本示例的循环部分是 for d in samples。分支逻辑走 match,穷尽性检查把漏掉的分支变成编译错误。

使用要点

  • 执行文件,main 会按顺序走完 human_readable。

常见问题

「把 Duration 格式化成人可读时长」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

主签名形如 fn human_readable(d: Duration) -> String

核心语句

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"),
}

代码示例

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));
    }
}