time icon indicating copy to clipboard operation
time copied to clipboard

Support providing default values during parsing

Open msrd0 opened this issue 1 year ago • 1 comments

I'm trying to parse a date in the format YYMMDD, e.g. 231022. While this crate can parse 20231022, it fails to parse 231022 (Playground):

use time::macros::{date, format_description};
use time::Date;

fn main() {
    let long_format = format_description!("[year][month][day]");
    assert_eq!(
        Date::parse("20231022", long_format).unwrap(),
        date!(2023 - 10 - 22)
    );

    let short_format = format_description!("[year repr:last_two][month][day]");
    assert_eq!(
        Date::parse("231022", short_format).unwrap(),
        date!(2023 - 10 - 22)
    );
}
thread 'main' panicked at src/main.rs:13:45:
called `Result::unwrap()` on an `Err` value: TryFromParsed(InsufficientInformation)

This is probably because there is no century information included in the later. It would be nice if it was possible to give default values during parsing, or add an option to assume missing values to be 0 (so I can add 2000 years after parsing) or similar. This would probably also make sense for formats with optional fields.

msrd0 avatar Oct 22 '23 17:10 msrd0

This is currently possible by going through Parsed struct. You would need to parse the format into Parsed, alter the year as necessary, and finally convert it to Date.

jhpratt avatar Oct 23 '23 05:10 jhpratt