The default duration unit is second.Also use below duration unit
Parse string to Duration
. The String duration unit support for one of:["y","mon","w","d","h","m","s", "ms", "µs", "ns"]
Also,duration_str
support time duration simple evaluation(+,*). See example:
toml
[dependencies]
duration-str = "0.3"
```rust use duration_str::parse; use std::time::Duration;
fn main() { let duration = parse("1d").unwrap(); assert_eq!(duration, Duration::new(24 * 60 * 60, 0));
let duration = parse("3m+31").unwrap(); //the default duration unit is second.
assert_eq!(duration, Duration::new(211, 0));
let duration = parse("3m + 31").unwrap(); //the default duration unit is second.
assert_eq!(duration, Duration::new(211, 0));
let duration = parse("3m + 13s + 29ms").unwrap();
assert_eq!(duration, Duration::new(193, 29 * 1000 * 1000 + 0 + 0));
let duration = parse("3m + 1s + 29ms +17µs").unwrap();
assert_eq!(
duration,
Duration::new(181, 29 * 1000 * 1000 + 17 * 1000 + 0)
);
let duration = parse("1m*10").unwrap(); //the default duration unit is second.
assert_eq!(duration, Duration::new(600, 0));
let duration = parse("1m*10ms").unwrap();
assert_eq!(duration, Duration::new(0, 600 * 1000 * 1000));
let duration = parse("1m * 1ns").unwrap();
assert_eq!(duration, Duration::new(0, 60));
let duration = parse("1m * 1m").unwrap();
assert_eq!(duration, Duration::new(3600, 0));
} ```
deserialize to std::time::Duration
```rust use durationstr::deserializeduration; use serde::*; use std::time::Duration;
struct Config { #[serde(deserializewith = "deserializeduration")] time_ticker: Duration, }
fn main() { let json = r#"{"timeticker":"1m+30"}"#; let config: Config = serdejson::fromstr(json).unwrap(); asserteq!(config.time_ticker, Duration::new(60 + 30, 0));
let json = r#"{"time_ticker":"1m+30s"}"#;
let config: Config = serde_json::from_str(json).unwrap();
assert_eq!(config.time_ticker, Duration::new(60 + 30, 0));
} ```
Also you can use deserialize_duration_chrono
function
```rust use chrono::Duration; use durationstr::deserializeduration_chrono; use serde::*;
struct Config { #[serde(deserializewith = "deserializedurationchrono")] timeticker: Duration, }
fn main() { let json = r#"{"timeticker":"1m+30"}"#; let config: Config = serdejson::fromstr(json).unwrap(); asserteq!(config.time_ticker, Duration::seconds(60 + 30)); } ```