Search code examples
c#timetimespantryparse

Checking string in the particular time format


I'm trying check is string(textBox1.Text) on the time format "hh:mm:ss", for send that string, as time parameter, in Sql query. I use TimeSpan.TryParseExact method:

        TimeSpan check;
        TimeSpan.TryParseExact(textBox1.Text, "hh:mm:ss", null, out check);
        if(check==null)   MessageBox.Show("incorrect time");
        else... 

But when I write to textbox 11 to the table adding the time 00:00:11 (11 seconds). I want so it's was incorrect time, correct is 00:00:11 line. How to do it's right?


Solution

  • You should use controls that are suitable for the task you're trying to do. For example, in this case, it may be easier and more consistent for users to use a DateTimePicker control instead of a TextBox.

    Set the DateTimePicker's Format property to Time and the ShowUpDown property to true. You can also do this in code as shown below.

    myTimePicker.Format = DateTimePickerFormat.Time;
    myTimePicker.ShowUpDown = true;
    

    You can also use the CustomFormat property to format the way you want the time displayed. If you use CustomFormat, you'll want to do this:

    myTimePicker.Format = DateTimePickerFormat.Custom; //instead of Time as above
    myTimePicker.CustomFormat = "hh:mm:ss"; //or whichever format you want