-4
//Example 2 - Validate Date for the format MM/DD/YYYY 
private bool ValidateDate(string stringDateValue)
{
   try
   {
       CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
       DateTime d = DateTime.ParseExact(stringDateValue, "MM/dd/yyyy", CultureInfoDateCulture);
       return true;
   }
   catch
   {
       return false;
   }
 }

How to set this code working without using the try and catch?

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Ruckus Maker
  • 25
  • 1
  • 6
  • 2
    Why do you want that? – Oscar Aug 05 '13 at 12:00
  • 1
    what is the issue of using it ? or why do you want to bypass? – aads Aug 05 '13 at 12:00
  • 1
    First of all, why do you want to avoid try catch block ?? – Pranav Aug 05 '13 at 12:01
  • Feel free to correct me if I am wrong, but I believe TryParseExact fails faster than throwing an exception would. I believe OP wishes to avoid the delay associated with exception handling. I know it is only very slight but over a large batch it might be important. – KingCronus Aug 05 '13 at 12:02
  • Also See: http://stackoverflow.com/questions/161942/how-slow-are-net-exceptions – KingCronus Aug 05 '13 at 12:04
  • 2
    It also goes against best practice, in most any language/framework, to manage control flow with exception handling that isn't really handling exceptions. – Grant Thomas Aug 05 '13 at 12:05

4 Answers4

9

Use DateTime.TryParseExact:

private bool ValidateDate(string stringDateValue)
{
    DateTime dummy;
    CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
    return DateTime.TryParseExact(stringDateValue, "MM/dd/yyyy",
                                  CultureInfoDateCulture, DateTimeStyles.None,
                                  out dummy);
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

Use DateTime.TryParseExact instead, which will let you control flow with a conditional if.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
0

You can try:

CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
DateTime date;

bool works = DateTime.TryParseExact(dateString, "MM/dd/yyyy", CultureInfoDateCulture , 
                       DateTimeStyles.None, out date))
Tamim Al Manaseer
  • 3,554
  • 3
  • 24
  • 33
0

i think the simpliest way is:

    private static bool ValidateDate(string stringDateValue)
    {
        DateTime dummy;
        return DateTime.TryParseExact(stringDateValue, "MM/dd/yyyy", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None,  out dummy);
    }
tray2002
  • 188
  • 6