|
| 1 | +// For the full copyright and license information, please view the LICENSE |
| 2 | +// file that was distributed with this source code. |
| 3 | + |
| 4 | +//! Parse an ISO 8601 date and time item |
| 5 | +//! |
| 6 | +//! The GNU docs state: |
| 7 | +//! |
| 8 | +//! > The ISO 8601 date and time of day extended format consists of an ISO 8601 |
| 9 | +//! > date, a ‘T’ character separator, and an ISO 8601 time of day. This format |
| 10 | +//! > is also recognized if the ‘T’ is replaced by a space. |
| 11 | +//! > |
| 12 | +//! > In this format, the time of day should use 24-hour notation. Fractional |
| 13 | +//! > seconds are allowed, with either comma or period preceding the fraction. |
| 14 | +//! > ISO 8601 fractional minutes and hours are not supported. Typically, hosts |
| 15 | +//! > support nanosecond timestamp resolution; excess precision is silently discarded. |
| 16 | +
|
| 17 | +use winnow::{combinator::alt, seq, PResult, Parser}; |
| 18 | + |
| 19 | +use crate::items::space; |
| 20 | + |
| 21 | +use super::{ |
| 22 | + date::{self, Date}, |
| 23 | + s, |
| 24 | + time::{self, Time}, |
| 25 | +}; |
| 26 | + |
| 27 | +#[derive(PartialEq, Debug, Clone)] |
| 28 | +pub struct DateTime { |
| 29 | + date: Date, |
| 30 | + time: Time, |
| 31 | +} |
| 32 | + |
| 33 | +pub fn parse(input: &mut &str) -> PResult<DateTime> { |
| 34 | + seq!(DateTime { |
| 35 | + date: date::iso, |
| 36 | + // Note: the `T` is lowercased by the main parse function |
| 37 | + _: alt((s('t').void(), (' ', space).void())), |
| 38 | + time: time::iso, |
| 39 | + }) |
| 40 | + .parse_next(input) |
| 41 | +} |
| 42 | + |
| 43 | +#[cfg(test)] |
| 44 | +mod tests { |
| 45 | + use super::{parse, DateTime}; |
| 46 | + use crate::items::{date::Date, time::Time}; |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn some_date() { |
| 50 | + let reference = Some(DateTime { |
| 51 | + date: Date { |
| 52 | + day: 10, |
| 53 | + month: 10, |
| 54 | + year: Some(2022), |
| 55 | + }, |
| 56 | + time: Time { |
| 57 | + hour: 10, |
| 58 | + minute: 10, |
| 59 | + second: 55.0, |
| 60 | + offset: None, |
| 61 | + }, |
| 62 | + }); |
| 63 | + |
| 64 | + for mut s in [ |
| 65 | + "2022-10-10t10:10:55", |
| 66 | + "2022-10-10 10:10:55", |
| 67 | + "2022-10-10 t 10:10:55", |
| 68 | + "2022-10-10 10:10:55", |
| 69 | + "2022-10-10 (A comment!) t 10:10:55", |
| 70 | + "2022-10-10 (A comment!) 10:10:55", |
| 71 | + ] { |
| 72 | + let old_s = s.to_owned(); |
| 73 | + assert_eq!(parse(&mut s).ok(), reference, "Failed string: {old_s}") |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments