https://github.com/poiscript/iso8601-duration
Parse ISO 8601 duration format.
https://github.com/poiscript/iso8601-duration
Last synced: 10 months ago
JSON representation
Parse ISO 8601 duration format.
- Host: GitHub
- URL: https://github.com/poiscript/iso8601-duration
- Owner: PoiScript
- Created: 2019-09-30T14:57:30.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2023-03-19T11:35:42.000Z (almost 3 years ago)
- Last Synced: 2025-03-18T05:13:02.875Z (10 months ago)
- Language: Rust
- Size: 12.7 KB
- Stars: 13
- Watchers: 2
- Forks: 5
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[](https://travis-ci.org/PoiScript/iso8601-duration)
[](https://docs.rs/iso8601-duration)
[](https://crates.io/crates/iso8601-duration)
# iso8601-duration
Parse ISO8601 duration format.
## Installation
```toml
iso8601-duration = "0.2.0"
```
## Usage
```rust
use iso8601_duration::Duration;
assert_eq!(
"P3Y6M4DT12H30M5S".parse(),
Ok(Duration::new(3., 6., 4., 12., 30., 5.))
);
assert_eq!("P23DT23H".parse::().unwrap().num_hours(), Some(575.));
assert_eq!("P0.5Y".parse::().unwrap().num_years(), Some(0.5));
assert_eq!("P0.5Y0.5M".parse::().unwrap().num_months(), Some(6.5));
assert_eq!("P12W".parse::().unwrap().num_days(), Some(84.));
assert!("PT".parse::().is_err());
assert!("P12WT12H30M5S".parse::().is_err());
assert!("P0.5S0.5M".parse::().is_err());
assert!("P0.5A".parse::().is_err());
```
## `year` and `month`
`Duration` can be converted to either `std::time::Duration` or
`chrono::Duration` by calling `to_std` or `to_chrono`.
Both `to_std` and `to_chrono` will return `None` if the duration
includes `year` and `month`. Because ISO8601 duration format allows
the usage of `year` and `month`, and these durations are non-standard.
Since months can have 28, 29 30, 31 days, and years can have either
365 or 366 days.
To perform a lossless conversion, a starting date must be specified:
```rust
// requires `chrono` feature
use iso8601_duration::Duration;
use chrono::DateTime;
let one_month: Duration = "P1M".parse().unwrap();
let date = DateTime::parse_from_rfc3339("2000-02-01T00:00:00Z").unwrap();
assert_eq!(
one_month.to_chrono_at_datetime(date).num_days(),
29 // 2000 is a leap year
);
```
License: MIT