rustdurationrust-chrono

How do I parse ISO 8601 duration strings using Chrono?


While chrono supports parsing of date, time and time zone in ISO 8601 compliant format, I am unable to find any method in the crate to parse duration strings such as PT2M which represents 2 minutes.


Solution

  • Chrono doesn't have any function to do this job.

    Instead, use the parse_duration crate to solve the problem:

    extern crate parse_duration;
    use parse_duration::parse;
    
    fn main() {
        print!("{:?}", parse("2 minutes"));
    }
    
    Ok(120s)
    

    Furthermore, there isn't any function that converts ISO 8601 shortcuts into a representation for the chrono or parse_duration crate.

    You need to write a parser that transforms the shortcuts like PT2M into a human readable form like 2 minutes, if you work with the parse_duration crate.

    If you want to use the chrono crate directly, you have a lot of calculation to do to put the duration into a numeric representation. I would take a look into the sources of parse in parse_duration.


    One workaround could be to calculate the duration out of two NaiveDates:

    extern crate chrono;
    use chrono::{Duration, NaiveDate};
    
    fn main() {
        let d = NaiveDate::from_ymd(2021, 8, 2);
        let tm1 = d.and_hms(0, 0, 0);
        let tm2 = d.and_hms(0, 2, 0);
        let delta: Duration = tm2.signed_duration_since(tm1);
        print!("{:?}", delta);
    }
    
    Duration { secs: 120, nanos: 0 }