Crates.io | duration-string |
lib.rs | duration-string |
version | 0.4.0 |
source | src |
created_at | 2020-03-27 13:06:33.469486 |
updated_at | 2024-05-22 15:37:03.314216 |
description | String to duration and vice-versa lib. Format is [0-9]+(ns|us|ms|[smhdwy]) such as 100ms, 1s, 2h, 1y |
homepage | |
repository | https://github.com/Ronniskansing/duration-string |
max_upload_size | |
id | 223497 |
size | 28,142 |
duration-string
is a library to convert from String
to Duration
and vice-versa.
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])
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"));
You can enable serialization/deserialization support by adding the feature serde
Add serde
feature
duration-string = { version = "0.4.0", features = ["serde"] }
Add derive to struct
use duration_string::DurationString;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Foo {
duration: DurationString
}
This project is licensed under the MIT License.
See LICENSE file for details.