Function jupiter::fmt::parse_duration
source · pub fn parse_duration(str: impl AsRef<str>) -> Result<Duration>
Expand description
Parses a duration from a given string.
This string can have the following suffixes:
- ms or MS: treats the value as milliseconds
- s or S: treats the value as seconds
- m or M: treats the value as minutes
- h or H: treats the value as hours
- d or D: treats the value as days
Returns an Err if either a non-integer value is given or if an unknow suffix was provided.
Examples
assert_eq!(jupiter::fmt::parse_duration("100 ms").unwrap(), Duration::from_millis(100));
assert_eq!(jupiter::fmt::parse_duration("12 s").unwrap(), Duration::from_secs(12));
assert_eq!(jupiter::fmt::parse_duration("3 M").unwrap(), Duration::from_secs(3 * 60));
assert_eq!(jupiter::fmt::parse_duration("2 H").unwrap(), Duration::from_secs(2 * 60 * 60));
assert_eq!(jupiter::fmt::parse_duration("5 d").unwrap(), Duration::from_secs(5 * 24 * 60 * 60));
// An invalid suffix results in an error...
assert_eq!(jupiter::fmt::parse_duration("3 Y").is_err(), true);
// Decimal numbers result in an error...
assert_eq!(jupiter::fmt::parse_duration("1.2s").is_err(), true);
// Negative numbers result in an error...
assert_eq!(jupiter::fmt::parse_duration("-1m").is_err(), true);