#duration #convert-string #format-duration #serde

duration-string

String to duration and vice-versa lib. Format is [0-9]+(ns|us|ms|[smhdwy]) such as 100ms, 1s, 2h, 1y

12 unstable releases (5 breaking)

new 0.5.2 Jan 8, 2025
0.5.1 Jan 8, 2025
0.4.0 May 22, 2024
0.3.0 Mar 22, 2023
0.0.6 Mar 28, 2020

#21 in Date and time

Download history 16837/week @ 2024-09-20 16639/week @ 2024-09-27 18259/week @ 2024-10-04 17762/week @ 2024-10-11 19460/week @ 2024-10-18 18350/week @ 2024-10-25 18841/week @ 2024-11-01 19708/week @ 2024-11-08 18387/week @ 2024-11-15 14344/week @ 2024-11-22 17750/week @ 2024-11-29 18794/week @ 2024-12-06 17966/week @ 2024-12-13 6762/week @ 2024-12-20 5126/week @ 2024-12-27 14547/week @ 2025-01-03

48,102 downloads per month
Used in 28 crates (16 directly)

Custom license

32KB
725 lines

duration-string

duration-string is a library to convert from String to Duration and vice-versa.

Uses zero dependencies unless serde feature is enabled.

build Crates.io

Takes a String such as 100ms, 2s, 5m 30s, 1h10m and converts it into a Duration.

Takes a Duration and converts it into String.

The String format is a multiply of [0-9]+(ns|us|ms|[smhdwy])

Example

String to Duration:

use std::convert::TryFrom;
use duration_string::DurationString;
use std::time::Duration;

let d: Duration = DurationString::try_from(String::from("100ms")).unwrap().into();
assert_eq!(d, Duration::from_millis(100));

// Alternatively
let d: Duration = "100ms".parse::<DurationString>().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 serialization/deserialization support by adding the feature serde

  • Add serde feature

    duration-string = { version = "0.5.2", features = ["serde"] }
    
  • Add derive to struct

    use duration_string::DurationString;
    use serde::{Deserialize, Serialize};
    
    #[derive(Serialize, Deserialize)]
    struct Foo {
      duration: DurationString
    }
    

License

This project is licensed under the MIT License.

See LICENSE file for details.

Dependencies

~150KB