[][src]Crate duration_string

duration-string is a string to duration and visa-versa lib.

Crates.io MIT licensed

Takes a string such as 100ms, 2s, 5m and converts it into a Duration Takes a duration and makes it into string.

The string format is [0-9]+(ms|[smhdwy])


String to duration

use duration_string::DurationString;
use std::time::Duration;
let d: Duration = DurationString::from_string(String::from("100ms")).unwrap().into();
assert_eq!(d, Duration::from_millis(100));

duration to string

use std::convert::TryFrom;
use duration_string::*;
use std::time::Duration;
let d: String = DurationString::from(Duration::from_millis(100)).into();
assert_eq!(d, String::from("100ms"));

Serde support

You can enable serialize/unserialize support by adding the feature serde

  • Add serde to the dependency duration-string = { version = "0.0.1", features = ["serde"] }
  • Add derive to struct
use serde::{Deserialize, Serialize};
use serde_json;
use duration_string::DurationString;

#[derive(Serialize, Deserialize)]
struct SerdeSupport {
    t: DurationString,
let s = SerdeSupport {
    t: DurationString::from_string(String::from("1m")).unwrap(),
assert_eq!(r#"{"t":"1m"}"#, serde_json::to_string(&s).unwrap());