5 个版本

0.0.6 2024 年 1 月 15 日
0.0.5 2024 年 1 月 15 日
0.0.4 2024 年 1 月 15 日
0.0.3 2024 年 1 月 15 日
0.0.2 2024 年 1 月 15 日

#98值格式化

29 每月下载量

MIT 许可证

21KB
494

humanize-duration

crates.io ci

将时间 Duration 转换为可读格式,并能够将输出字符串截断到特定的时间单位。
它支持 time::Durationcore::time::Durationchrono::Duration(使用 chrono 功能)

示例

    use humanize_duration::Truncate;
    use humanize_duration::prelude::DurationExt;

    pub fn main() {
        let duration = time::Duration::nanoseconds(131_200_001_301_021_123);
        let human = duration.human(Truncate::Nano);
        println!("duration: {}", human);
    }

它将打印:4years 1month 27days 2h 36m 17s 301ms 21µs 123ns

    use humanize_duration::Truncate;
    use humanize_duration::prelude::DurationExt;
    
    pub fn main() {
        let duration = time::Duration::nanoseconds(131_200_001_301_021_123);
        let human2 = duration.human(Truncate::Day);
        println!("duration: {}", human2);
    }

它将打印:4years 1month 27days

自定义 格式化也是可能的。例如

    use humanize_duration::{*};
    use humanize_duration::prelude::DurationExt;
    use humanize_duration::types::DurationParts;

    use time::Duration as TimeDuration;
    struct MyFormatter;

    unit!(MyYear, " anno", " anni");
    unit!(MyMonth, " mese", " mesi");
    unit!(MyDay, " giorno", " giorni");
    unit!(MyHour, " ora", " ore");
    unit!(MyMinute, " minuto", " minuti");
    unit!(MySecond, " secondo", " secondi");
    unit!(MyMillis, " millisecondo", " millisecondi");
    unit!(MyMicro, " microsecondo", " microsecondi");
    unit!(MyNano, " nanosecondo", " nanosecondi");

    impl Formatter for MyFormatter {
        fn get(&self, truncate: Truncate) -> Box<dyn Unit> {
            match truncate {
                Truncate::Nano => Box::new(MyNano),
                Truncate::Micro => Box::new(MyMicro),
                Truncate::Millis => Box::new(MyMillis),
                Truncate::Second => Box::new(MySecond),
                Truncate::Minute => Box::new(MyMinute),
                Truncate::Hour => Box::new(MyHour),
                Truncate::Day => Box::new(MyDay),
                Truncate::Month => Box::new(MyMonth),
                Truncate::Year => Box::new(MyYear),
            }
        }

        fn format(&self, f: &mut std::fmt::Formatter<'_>, parts: DurationParts, truncate: Truncate) -> std::fmt::Result {
            self.format_default(f, parts, truncate)
        }
    }

    pub fn main() {
        let duration = TimeDuration::nanoseconds(150_345_202_557_001);
        let human = duration.human_with_format(Truncate::Nano, MyFormatter);
        println!("human: {human}");
    }

它将打印:1 giorno 17 ore 45 minuti 45 secondi 202 millisecondi 557 microsecondi 1 nanosecondo

依赖

~0.7–1MB
~17K SLoC