0

I am trying to capture input data from a Textbox by converting it to DateTime format

string yy = string.Format("{0:T}", textBox1.Text);

I wish to use Try-Catch-Finally to produce an Systm.FormatException error and display it in another text box

try 
{
 DateTime XF = Convert.ToDateTime(yy); 
}
 catch (FormatException)    
       { 
       textBox5.Text = "incorrect time"; 
       }
   finally 
          {
           DateTime XF = Convert.ToDateTime(yy); 
           textBox5.Text = Convert.ToString(XF.Hour + XF.Minute + XF.Second); 
          }

How should i go around?

Thanks

9to5ios
  • 5,319
  • 2
  • 37
  • 65
Rajiv S Mehta
  • 50
  • 2
  • 7

4 Answers4

2

Instead of using an exception to do this, it'd be better to use DateTime.TryParse. This will return a simple true or false if it can be converted into a date.

http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

DateTime xf;
bool canBeConverted = DateTime.TryParse(yy, out xf);
if (!canBeConverted) { textBox5.Text = "incorrect time"; }
Arran
  • 24,648
  • 6
  • 68
  • 78
  • 1
    I doubt that it actually swallows any exceptions. Using ILSpy, I found _no_ exceptions being catched inside the `TryParse` functions or their called functions. – Uwe Keim Apr 12 '13 at 09:35
  • @UweKeim You are right, the whole point of TryParse is that no exception is thrown. – Rik Apr 12 '13 at 11:17
0

You should use DateTime.TryParse() or DateTime.TryParseExact() if you're not sure if the format is correct. There's no need for exceptions, which are slow and less clear.

string dateString;
DateTime result;
if (DateTime.TryParse(dateString, result))
{
    // it's a recognized as a DateTime
}
else
{
    // it's not recognized as a DateTime
}
Rik
  • 28,507
  • 14
  • 48
  • 67
0

You can consider using DateTime.TryParseExact or DateTime.TryParse Method.

Eg.:

    string dateString = "Mon 16 Jun 8:30 AM 2008";
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
    DateTimeStyles.None, out dateTime))
{
    textBox5.Text = "correct time";
}
    else
      textBox5.Text = "incorrect time";
Kapil Khandelwal
  • 15,958
  • 2
  • 45
  • 52
0

Try using DateTime.TryParse() method.

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
johnpm45
  • 1
  • 2