iso8601_duration/
lib.rs

1//! Parse ISO8601 duration format.
2//!
3//! <https://en.wikipedia.org/wiki/ISO_8601#Durations>
4//!
5//! # Installation
6//!
7//! ```toml
8//! iso8601-duration = "0.2.0"
9//! ```
10//!
11//! # Usage
12//!
13//! ```rust
14//! use iso8601_duration::Duration;
15//!
16//!  assert_eq!(
17//!      "P3Y6M4DT12H30M5S".parse(),
18//!      Ok(Duration::new(3., 6., 4., 12., 30., 5.))
19//!  );
20//!  assert_eq!("P23DT23H".parse::<Duration>().unwrap().num_hours(), Some(575.));
21//!  assert_eq!("P0.5Y".parse::<Duration>().unwrap().num_years(), Some(0.5));
22//!  assert_eq!("P0.5Y0.5M".parse::<Duration>().unwrap().num_months(), Some(6.5));
23//!  assert_eq!("P12W".parse::<Duration>().unwrap().num_days(), Some(84.));
24//!
25//!  assert!("PT".parse::<Duration>().is_err());
26//!  assert!("P12WT12H30M5S".parse::<Duration>().is_err());
27//!  assert!("P0.5S0.5M".parse::<Duration>().is_err());
28//!  assert!("P0.5A".parse::<Duration>().is_err());
29//! ```
30//!
31//! # `year` and `month`
32//!
33//! `Duration` can be converted to either `std::time::Duration` or
34//! `chrono::Duration` by calling `to_std` or `to_chrono`.
35//!
36//! Both `to_std` and `to_chrono` will return `None` if the duration
37//! includes `year` and `month`. Because ISO8601 duration format allows
38//! the usage of `year` and `month`, and these durations are non-standard.
39//! Since months can have 28, 29 30, 31 days, and years can have either
40//! 365 or 366 days.
41//!
42//! To perform a lossless conversion, a starting date must be specified:
43//!
44//! ```rust
45//! // requires `chrono` feature
46//!
47//! use iso8601_duration::Duration;
48//! use chrono::DateTime;
49//!
50//! let one_month: Duration = "P1M".parse().unwrap();
51//! let date = DateTime::parse_from_rfc3339("2000-02-01T00:00:00Z").unwrap();
52//! assert_eq!(
53//!     one_month.to_chrono_at_datetime(date).num_days(),
54//!     29 // 2000 is a leap year
55//! );
56//! ```
57
58#[cfg(feature = "chrono")]
59mod chrono;
60mod duration;
61#[cfg(feature = "serde")]
62mod serde;
63
64pub use crate::duration::{Duration, ParseDurationError};