dur
Dur is a human-readable duration parser and formatter/pretty-printer.
no_std Support
Dur works without std! However, alloc is still required for now (it's used in the Error type for better error messages).
Examples
// StdDuration is a re-export of core::time::Duration
use ;
// Parsing
let d = "1m 42s"..unwrap;
assert_eq!;
// Duration::to_std and Duration::from_std convert to and from std's Duration:
assert_eq!;
assert_eq!;
// Formatting
assert_eq!;
// The alternate formatter `#` makes it use full units:
assert_eq!;
// Fractions work:
let d = "5.1230 secs"..unwrap;
assert_eq!;
// Without any precision formatter, at most 2 digits after the decimal point are printed:
assert_eq!;
// We can specify precision:
assert_eq!;
// Trailling zeros are removed while formatting
let d = "1.2000 milliseconds"..unwrap;
assert_eq!;
// The precision specifier is considered "maximum number of digits after the decimal point"
// so, trailling zeroes are still removed!
assert_eq!;
// Durations are normalized to human readable forms:
let hour = "3600 seconds"..unwrap;
assert_eq!;
// IF the string contains only a single integer, no unit, it's parsed as milliseconds:
assert_eq!;
// However if there's more than one value, it's an error:
assert_eq!;
// Negative values aren't allowed:
assert_eq!;
// Duration implements arithmetic traits:
let mut d = from_secs;
d += from_millis;
d -= from_millis;
assert_eq!;
d /= 2_u32;
assert_eq!;
assert_eq!;
// You can add/subtract StdDuration as well:
let sd = from_millis;
assert_eq!;
// It's implemented both ways:
assert_eq!;
// You can add/sub Duration from a SystemTime:
let mut now = now;
now -= from_secs;
now += from_secs;
// Finally, you can also compare Duration and StdDuration:
assert_eq!;
Optional Features
std: MakesErrorimplementstd::error::Error.serde: Enables serde de/serialization for [Duration].clapEnables usingDurationdirectly as anArgin clap.
Syntax
Dur understands durations of the form "N UNIT" or "N1 UNIT1 N' UNIT2".
Spaces between numbers and units are optional.
Numbers can be decimal: 1.2, .5, 5..
Numbers cannot be negative.
Units are case insensitive.
Supported units:
- nanoseconds, nanosecond, nanos, ns
- microseconds, microsecond, micros, us, µs
- milliseconds, millisecond, millis, ms
- second, seconds, secs, sec, s
- minutes, minute, mins, min, m
- hours, hour, hrs, hr, h
- days, day, d
- weeks, week, w
- years, year, yrs, yr, y
One exception is with strings that contain only one non-negative integer (e.g. "1234"): these are parsed as milliseconds.