Checking valid Date.

vishalneeraj-24503
Posted by vishalneeraj-24503 under C# category on | Points: 40 | Views : 1507
protected bool Is_Valid_Date(String date)
{
try
{
DateTime dt = DateTime.Parse(date);
return true;
}
catch
{
return false;
}
}


In above code,if valid date is passed then DateTime.Parse will parse date and cursor will move to the next line and return true.If we pass any wrong date or pass integer value or string value,then DateTime.Par se will throw an error and will go in a catch block.

Comments or Responses

Posted by: kgovindarao523-21772 on: 12/4/2014 Level:Bronze | Status: [Member] [MVP] | Points: 10
Hi,
Instead of using try catch blocks there is a feasibility in C# to check the date validation including required format, using TryParse Method.
Why shouldn't we use that.
protected bool Is_Valid_Date(String date)
{
DateTime dateTime;
if (DateTime.TryParse(date, out dateTime))
{
return true; // Parsed DateTime Value can be accessed here in dateTime
}else{
return false;
}
}


Login to post response