Jiff: checking iso date

Let's say I like to parse an iso date in order to learn if the iso date specified is valid.

Example: 2025-02-12 is valid. Both 2025-02-29 (2025 no leap year) and 2025-05-32 are not valid.

I can use

    jiff::fmt::strtime::parse("%Y-%m-%d", "2025-02-12")?;

It checks ok in most cases except it doesn't detect invalid February dates.

What it the best way to detect invalid February date here?

Some testing indicates that to_date detects invalid days.

That's returning a jiff::fmt::strtime::BrokenDownTime, which is a representation of the parsed components. If you ask for a date, you'll get an error. Similarly, if you try to strptime directly into a date, you'll get an error. Or more simply, forget about strptime entirely and just try to parse into a date (which uses ISO 8601):

fn main() {
    let tm = jiff::fmt::strtime::parse("%Y-%m-%d", "2025-02-29")?;
    assert!(tm.to_date().is_err());

    let result = jiff::civil::Date::strptime("%Y-%m-%d", "2025-02-29");
    assert!(result.is_err());

    assert!("2025-02-29".parse::<jiff::civil::Date>().is_err());
}
5 Likes

Aah. Such easy. Thanks a lot.

1 Like