vikram vikram - 8 months ago 38
C# Question

How to validate DateTime for a leap year

I'm working with C# and I'm trying to find whether the given date and month is valid for a leap year. This is my code:

static void Main(string[] args)
Console.WriteLine("The following program is to find whether the Date and Month is Valid for an LEAP YEAR");
Console.WriteLine("Enter the Date");
int date = Convert.ToInt16(Console.ReadLine()); //User values for date and month
Console.WriteLine("Enter the Month");
int month = Convert.ToInt16(Console.ReadLine());
if (month == 2 && date < 30) //Determination of month and date of leap year using If-Else
Console.WriteLine("Your input is valid");
else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && date < 32)
Console.WriteLine("Your inpput valid1");
else if (( month == 4 || month == 6 || month == 9 || month == 11 ) && date < 31)
Console.WriteLine("Your inpput valid2");
Console.WriteLine("Your input INvalid");


My question is, can I use
for this program or is this a better way? Any suggestions are welcome.


I would suggest taking the input as a string and then using the DateTime.TryParse method. DateTime.TryParse accepts a string and an out DateTime (out keyword), and returns true if the string input was both correctly parsed and is a valid DateTime, and false otherwise.

From the documentation:

If s is the string representation of a leap day in a leap year in the current calendar, the method parses s successfully. If s is the string representation of a leap day in a non-leap year in the current culture's current calendar, the parse operation fails and the method returns false.

Usage example:

Console.WriteLine("Please enter a date.");

string dateString = Console.ReadLine();
DateTime dateValue;

if (DateTime.TryParse(dateString, out dateValue))
    // Hooray, your input was recognized as having a valid date format,
    // and is a valid date! dateValue now contains the parsed date
    // as a DateTime.
    Console.WriteLine("You have entered a valid date!");
    // Aww, the date was invalid.
    Console.WriteLine("The provided date could not be parsed.");