Convert milliseconds to a human-readable string — 1337000000 → "15d 11h 23m 20s". A faithful Rust port of the pretty-ms
npm package, with the same options. Zero dependencies.
use pretty_ms::{pretty_ms, Options};
assert_eq!(pretty_ms(1_337_000_000.0, &Options::default()), "15d 11h 23m 20s");
assert_eq!(pretty_ms(1337.0, &Options::default()), "1.3s");
assert_eq!(pretty_ms(1000.0, &Options::default().verbose(true)), "1 second");
assert_eq!(pretty_ms(95_500.0, &Options::default().colon_notation(true)), "1:35.5");There is also a Duration
wrapper:
use std::time::Duration;
use pretty_ms::{pretty_duration, Options};
assert_eq!(pretty_duration(Duration::from_secs(90), &Options::default()), "1m 30s");Showing a raw millisecond count to a human is unfriendly. This turns it into the
familiar 15d 11h 23m 20s (or 15:11:23:20, or 15 days …), matching the
ubiquitous JS library's output exactly — handy when you want parity with a
JavaScript front-end, or just a well-tested, option-rich duration formatter.
[dependencies]
pretty-ms = "0.1"Build with [Options::default()] and chain the setters:
| Option | Effect |
|---|---|
compact |
Only the first unit: 1h 10m → 1h |
unit_count(n) |
Show at most n units |
verbose |
Long unit names: 5h 1m → 5 hours 1 minute |
colon_notation |
5h 1m 45s → 5:01:45 |
seconds_decimal_digits(n) |
Fraction digits on seconds (default 1) |
milliseconds_decimal_digits(n) |
Fraction digits on milliseconds (default 0) |
keep_decimals_on_whole_seconds |
3s → 3.0s |
separate_milliseconds |
1s 51ms instead of 1.05s |
format_sub_milliseconds |
Show µs and ns |
hide_year / hide_year_and_days / hide_seconds |
Drop those units |
use pretty_ms::{pretty_ms, Options};
assert_eq!(pretty_ms(1_337_000_000.0, &Options::default().compact(true)), "15d");
assert_eq!(pretty_ms(1010.0, &Options::default().separate_milliseconds(true)), "1s 10ms");
assert_eq!(pretty_ms(100.4, &Options::default().format_sub_milliseconds(true)), "100ms 400µs");Negative values get a leading -, and a non-finite input is treated as 0.
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
Tung Tran 💻 🚧 |
Licensed under either of Apache-2.0 or MIT at your option.