#duration-parser #duration #human-friendly #human-readable #parser #macro

duration-human

为与人类交互而设计的Duration包装器

7个版本

0.1.10 2022年12月10日
0.1.9 2022年12月10日

日期和时间 中排名第287

Download history 217/week @ 2024-03-14 234/week @ 2024-03-21 245/week @ 2024-03-28 235/week @ 2024-04-04 325/week @ 2024-04-11 260/week @ 2024-04-18 271/week @ 2024-04-25 392/week @ 2024-05-02 228/week @ 2024-05-09 392/week @ 2024-05-16 356/week @ 2024-05-23 526/week @ 2024-05-30 423/week @ 2024-06-06 436/week @ 2024-06-13 302/week @ 2024-06-20 157/week @ 2024-06-27

每月下载量1,406
4 个 Crate中使用

自定义许可

33KB
644

人类使用的Duration包装器

std::time::Duration的包装器,用于处理人类可读形式的时间长度

DurationHuman

解析和格式化以进行人类交互

主要目标是声明一个从,以及格式化为,人类可读字符串的Duration。

解析字符串时,将所有带有时间单位的值加到总持续时间上,因此解析("1min 2s 1min")的结果为122s持续时间。

将字符串格式化为使用可以表示整数值的单位,因此122s的持续时间将格式化为122s,但86400s的持续时间将格式化为1天。

将字符串格式化为美观打印包括所有具有非零值的单位,因此122s将美观打印为"2min 2s",而90060将打印为"1天 1小时 1分钟"。

# use duration_human::DurationHuman;
let duration = DurationHuman::try_from("80h").unwrap();
assert_eq!(format!("{:#}", duration), "3 days 8h".to_string());
assert_eq!(format!("{}", duration), "80h".to_string());
let duration = DurationHuman::try_from("72h").unwrap();
assert_eq!(format!("{:#}", duration), "3 days".to_string());
assert_eq!(format!("{}", duration), "3 days".to_string());
let duration = DurationHuman::try_from("18446744073709551615ns").unwrap();
assert_eq!(format!("{:#}", duration), "5 centuries 84 years 11 months 1 week 6 days 23h 34min 33s 709ms 551μs 615ns".to_string());
// precision is nano second
let duration = DurationHuman::try_from("604800μs").unwrap();
assert_eq!(format!("{:#}", duration), "604ms 800μs".to_string());
assert_eq!(duration.to_string(), "604800μs".to_string());
let duration = DurationHuman::try_from("604800ms").unwrap();
assert_eq!(format!("{:#}", duration), "10min 4s 800ms".to_string());
assert_eq!(duration.to_string(), "604800ms".to_string());
let duration = DurationHuman::try_from("604800s").unwrap();
assert_eq!(format!("{:#}", duration), "1 week".to_string());
let duration = DurationHuman::try_from("604800s").unwrap();
assert_eq!(format!("{:#}", duration), "1 week".to_string());
assert_eq!(format!("{}", duration), "1 week".to_string());
let duration = DurationHuman::try_from("608430s").unwrap();
assert_eq!(format!("{:#}", duration), "1 week 1h 30s".to_string());
assert_eq!(format!("{}", duration), "608430s".to_string());

添加到Instant

std::time::Instant支持Add,但我们不能在这里操作,所以我们将它反过来

use std::time::Instant;
use duration_human::{DurationHuman, DurationError};

let instant = Instant::now();
let duration = DurationHuman::try_from("420s")?;
let after = duration + instant;
let diff = DurationHuman::from(after - instant);
assert_eq!(format!("{}", diff), format!("7min"));

依赖关系

~3.5–5MB
~87K SLoC