5 releases

0.2.0 Mar 16, 2021
0.1.4 Mar 15, 2021
0.1.3 Mar 11, 2021
0.1.1 Mar 11, 2021
0.1.0 Mar 11, 2021

#45 in Date and time

Download history 76/week @ 2021-03-11 10/week @ 2021-03-18 26/week @ 2021-03-25 1/week @ 2021-04-01 9/week @ 2021-04-08 24/week @ 2021-04-15 21/week @ 2021-04-22 13/week @ 2021-04-29 14/week @ 2021-05-06 43/week @ 2021-05-13 23/week @ 2021-05-20 27/week @ 2021-05-27 11/week @ 2021-06-03 25/week @ 2021-06-10

65 downloads per month

MIT AND Apache-2.0

18KB
304 lines

parse string to std::time::Duration

Chrono GitHub Actions Crates.io Docs.rs

Parse string to Duration . The String value unit support for one of:[y,mon,w,d,h,m,s]

  • y:Year. Support string value: ["y" | "year" | "Y" | "YEAR" | "Year"]. e.g. 1y
  • mon:Month.Support string value:["mon" | "MON" | "Month" | "month" | "MONTH"]. e.g. 1mon
  • w:Week.Support string value: ["w" | "W" | "Week" | "WEEK" | "week"]. e.g. 1w
  • d:Day.Support string value: ["d" | "D" | "Day" | "DAY" | "day"]. e.g. 1d
  • h:Hour.Support string value: ["h" | "H" | "Hour" | "HOUR" | "hour"]. e.g. 1h
  • m:Minute.Support string value: ["m" | "M" | "Minute" | "MINUTE" | "minute"]. e.g. 1m
  • m:Second.Support string value: ["s" | "S" | "Second" | "SECOND" | "second"]. e.g. 1s

Also,duration_str support time duration simple evaluation(+,*). See example:

example

[dependencies]
duration-str = "0.2" 
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();
    assert_eq!(duration,Duration::new(211,0));

    let duration = parse("3m + 31").unwrap();
    assert_eq!(duration,Duration::new(211,0));

    let duration = parse("1m*10").unwrap();
    assert_eq!(duration,Duration::new(600,0));

    let duration = parse("1m * 10").unwrap();
    assert_eq!(duration,Duration::new(600,0));
}

deserialize in struct

deserialize to std::time::Duration

use duration_str::deserialize_duration;
use serde::*;
use std::time::Duration;

#[derive(Debug, Deserialize)]
struct Config {
    #[serde(deserialize_with = "deserialize_duration")]
    time_ticker: Duration,
}

fn main() {
    let json = r#"{"time_ticker":"1m+30"}"#;
    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

use chrono::Duration;
use duration_str::deserialize_duration_chrono;
use serde::*;

#[derive(Debug, Deserialize)]
struct Config {
    #[serde(deserialize_with = "deserialize_duration_chrono")]
    time_ticker: Duration,
}

fn main() {
    let json = r#"{"time_ticker":"1m+30"}"#;
    let config: Config = serde_json::from_str(json).unwrap();
    assert_eq!(config.time_ticker, Duration::seconds(60 + 30));
}

Dependencies

~4.5MB
~88K SLoC