C# Program: Convert user input to datetime with exception handling
Write a C# program that creates a method that reads a date from the user in the format "dd/mm/yyyy" and converts it to a DateTime object. Handle an exception if the input format is invalid.
Sample Solution:
C# Sharp Code:
using System;
class Program {
static void Main() {
try {
// Prompt the user to input a date in a specific format (dd/mm/yyyy)
Console.Write("Input a date (format-> dd/mm/yyyy): ");
string input = Console.ReadLine();
// Convert the user-input string to a DateTime object using the ConvertToDate method
DateTime date = ConvertToDate(input);
// Display the formatted date to the user
Console.WriteLine("Date: " + date.ToShortDateString());
} catch (FormatException) {
// Catch block for handling FormatException (invalid date format)
Console.WriteLine("Error: Invalid date format. Please input a valid date in the format dd/mm/yyyy.");
} catch (Exception ex) {
// Catch block for handling other types of exceptions
Console.WriteLine("An error occurred: " + ex.Message);
}
}
// Method to convert a string to a DateTime object based on a specific format
static DateTime ConvertToDate(string input) {
// Define the date format expected from the user input
string[] format = { "dd/MM/yyyy" };
// Parse the input string to a DateTime object using the specified format
return DateTime.ParseExact(input, format, null, System.Globalization.DateTimeStyles.None);
}
}
Sample Output:
Input a date (format-> dd/mm/yyyy): 11/01/2019 Date: 11-01-2019
Input a date (format-> dd/mm/yyyy): 11/14/2019 Error: Invalid date format. Please input a valid date in the format dd/mm/yyyy.
Input a date (format-> dd/mm/yyyy): 00/00/2019 Error: Invalid date format. Please input a valid date in the format dd/mm/yyyy.
Input a date (format-> dd/mm/yyyy): 01-01-2019 Date: 01-01-2019
Explanation:
In the above exercise -
- The "Main()" method prompts the user to enter a date in the format "dd/mm/yyyy" using Console.Write() and Console.ReadLine(). The input is stored in the input variable.
- The program calls the ConvertToDate method, passing the input string as an argument.
- The ConvertToDate method uses DateTime.ParseExact to convert the string to a DateTime object, specifying the desired format "dd/MM/yyyy". If the input string cannot be parsed according to the specified format, a FormatException is thrown.
- In the "Main()" method, exceptions are handled using catch blocks. If a FormatException occurs, it means the input date format was invalid. The program catches this exception and displays an appropriate error message.
- Any other exceptions are caught by the generic catch block, and a general error message is displayed.
- The program displays the converted DateTime object using ToShortDateString() to format it as a short date string.
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Divide two numbers with exception handling.
Next: Calculate square root with exception handling.
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