pub fn str_to_duration(s: &str) -> Result<Duration, StrToDurationError>
Expand description
Take a string with a simple duration format (single number followed by unit)
and output a StdDuration
. Accepts durations in minutes (m), hours
(h), days (d), weeks (w), months (mon), or years (y).
A month is equivalent to 30 days. A year is equivalent to 365 days.
ยงExamples
Basic (small numbers that fit within the unit)
use bobashare_web::str_to_duration;
use chrono::TimeDelta;
assert_eq!(
TimeDelta::from_std(str_to_duration("17m")?)?,
TimeDelta::minutes(17),
);
assert_eq!(
TimeDelta::from_std(str_to_duration("14h")?)?,
TimeDelta::hours(14),
);
assert_eq!(
TimeDelta::from_std(str_to_duration("26d")?)?,
TimeDelta::days(26),
);
assert_eq!(
TimeDelta::from_std(str_to_duration("2w")?)?,
TimeDelta::weeks(2),
);
assert_eq!(
TimeDelta::from_std(str_to_duration("4mon")?)?,
TimeDelta::days(30 * 4),
);
assert_eq!(
TimeDelta::from_std(str_to_duration("7y")?)?,
TimeDelta::days(365 * 7),
);
Demonstrate the day values of months and years
assert_eq!(
TimeDelta::from_std(str_to_duration("1mon")?)?,
TimeDelta::days(30),
);
assert_eq!(
TimeDelta::from_std(str_to_duration("1y")?)?,
TimeDelta::days(365),
);