time-rs / time

The most used Rust library for date and time handling.
https://time-rs.github.io
Apache License 2.0
1.06k stars 261 forks source link

Support providing default values during parsing #632

Open msrd0 opened 9 months ago

msrd0 commented 9 months ago

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.

jhpratt commented 9 months ago

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.