walkair
walkair

Reputation: 652

Rust chrono::NaiveTime::parse_from_str() fails to parse PM

While parsing strings with Rust chrono::NaiveTime::parse_from_str(), it appears that parsing AM works but PM doesn't work (returns ParseErrorKind::Impossible). Is there a reason for the following failure?

The first example time_am is a time string with AM that parses correctly.

The second example time_pm is a time string with PM that fails to parse.

fn main() {
    let time_am = chrono::NaiveTime::parse_from_str("08:30 AM", "%H:%M %p");
    println!(
        "time_am: {}",
        match time_am {
            Ok(time) => time.to_string(),
            Err(error) => error.to_string(),
        }
    );

    let time_pm = chrono::NaiveTime::parse_from_str("08:30 PM", "%H:%M %p");
    println!(
        "time_pm: {}",
        match time_pm {
            Ok(time) => time.to_string(),
            Err(error) => error.to_string(),
        }
    );
}

Result:

time_am: 08:30:00
time_pm: no possible date and time matching input

That error string corresponds to the following line in chrono mod.rs:

ParseErrorKind::Impossible => write!(f, "no possible date and time matching input"),

Upvotes: 1

Views: 399

Answers (1)

walkair
walkair

Reputation: 652

I found the answer myself, shortly after posting the question. The problem is that the use of %H corresponds to 24-hour time. I need to use %I for 12-hour time.

Upvotes: 1

Related Questions