Rust Date Parser: Handling user input and Parsing errors
Write a Rust program that accepts user input for a date, parses it, and prints it in a different format, handling parsing errors.
Sample Solution:
Rust Code:
use std::io;
fn main() {
println!("Please enter a date in the format YYYY-MM-DD:");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read input.");
// Trim any leading or trailing whitespace from the input
let trimmed_input = input.trim();
// Attempt to parse the input date
match parse_date(trimmed_input) {
Ok(parsed_date) => println!("Parsed date: {}", parsed_date),
Err(err) => eprintln!("Error parsing date: {}", err),
}
}
fn parse_date(date_str: &str) -> Result<String, &str> {
// Attempt to split the date string into its components
let parts: Vec<&str> = date_str.split('-').collect();
// Check if the date string has three components
if parts.len() != 3 {
return Err("Invalid date format. Please use YYYY-MM-DD.");
}
// Attempt to parse the components into integers
let year: i32 = match parts[0].parse() {
Ok(year) => year,
Err(_) => return Err("Invalid year."),
};
let month: u32 = match parts[1].parse() {
Ok(month) if (1..=12).contains(&month) => month,
_ => return Err("Invalid month."),
};
let day: u32 = match parts[2].parse() {
Ok(day) if (1..=31).contains(&day) => day,
_ => return Err("Invalid day."),
};
// Format the parsed date components
let parsed_date = format!("{}-{:02}-{:02}", year, month, day);
Ok(parsed_date)
}
Output:
Please enter a date in the format YYYY-MM-DD: 2000-02-02 Parsed date: 2000-02-02
Please enter a date in the format YYYY-MM-DD: 2001-13-12 Compiling playground v0.0.1 (/playground) Finished dev [unoptimized + debuginfo] target(s) in 0.65s Running `target/debug/playground` Error parsing date: Invalid month.
Please enter a date in the format YYYY-MM-DD: 2001-02-32 Compiling playground v0.0.1 (/playground) Finished dev [unoptimized + debuginfo] target(s) in 0.58s Running `target/debug/playground` Error parsing date: Invalid day.
Explanation:
Here's a brief explanation of the above Rust code:
- The main function:
- Prints a message asking the user to enter a date.
- Reads the user input from the console.
- Trims any leading or trailing whitespace from the input.
- Calls the "parse_date()" function to attempt to parse the input date.
- Prints either the parsed date or an error message depending on the result of the parsing.
- The parse_date function:
- Attempts to split the input date string into its components (year, month, day) based on the '-' delimiter.
- Checks if the date string has exactly three components. If not, it returns an error indicating an invalid date format.
- Attempts to parse each component into integers (year, month, day).
- Validates the parsed year, month, and day:
- For the year, it checks if it can be parsed into an integer.
- For the month, it checks if it falls within the range of 1 to 12 (inclusive).
- For the day, it checks if it falls within the range 1 to 31 (inclusive).
- If any parsing or validation fails, it returns an error with an appropriate error message.
- If parsing and validation succeed, it formats the parsed date components into the YYYY-MM-DD format and returns it as a "String".
Rust Code Editor:
Previous: Rust Function: Safe Division with Error handling.
Next: Rust JSON Parsing Program: Read, Parse, and Print Specific data.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics