Checking wether a user typed in correct formatted time

How do one go about checking wether or not the user typed in a valid time like "hh:mm:ss" what ive tried is:

string format = "hh:mm:ss";
static bool ValidateTime(string time, string format)
        {
            DateTime outTime;
            return DateTime.TryParseExact(time, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out outTime);
        }

then checking wether it returnes true or false:

 bool result = ValidateTime(redigerINDtextbox.Text, format);

        if (result)
        {
            redigerINDtextbox.Text = "yay";
        }
        else
            redigerINDtextbox.Text = "nay";

It always returns false, when parsing in "7:17:05" or even "14:23:23" for example.

Upvotes: 2

Views: 50

Answers (2)

anon
anon

Reputation: 865

Because you're using DateTime

Try this

string format = "hh:mm:ss";
static bool ValidateTime(string time, string format)
{
TimeSpan times;
return TimeSpan.TryParseExact(time,
                                    format,
                                    CultureInfo.InvariantCulture,
                                    out times);
}

Upvotes: 1

Kevin Gosse
Kevin Gosse

Reputation: 39007

hh is for 12-hour clock, so "14:23:23" can't be parsed. For 24-hour clock, use HH:

string format = "HH:mm:ss";

Upvotes: 2

Related Questions