Link to home
Start Free TrialLog in
Avatar of Nugs
Nugs

asked on

Check if string is in time formate (01:00:00)

I need to check if a string in in a time format of 01:00:00 to 24:00:00. In addition i need the check to throw a true or false as it is in a If statement.

Nugs
Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

A typical way to do this would be to use a Regular Expression.

I assume you mean RETURN true or false rather than THROW true or false.
A very quick and dirty check on a string in a variable called "foo" would be
Regex.IsMatch(foo, "[0-2][0-9]:[0-5][0-9]:[0-5][0-9]", RegexOptions.None)
but this will allow some invalid values to slip by...
such as 29:00:00, for example.
More CORRECT but not as easy to understand is
Regex.IsMatch(foo, "([0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9]", RegexOptions.None)
which allows ALL hours beginning with 0 or 1, but requires a singels digit of 0-4 if the hour begins with "2".

You might refine this  using the "|" alternation if you want to disallow, say 24:00:01, or if you want to ALLOW 1:00:00 or 12:1:2 (not require leading zeroes).
Avatar of Nugs
Nugs

ASKER

Yes i do mean Return... the ONLY values that i will need to check are as follows:

01:00:00
02:00:00
03:00:00
04:00:00
05:00:00
06:00:00
07:00:00
08:00:00
09:00:00
10:00:00
11:00:00
12:00:00
13:00:00
14:00:00
15:00:00
16:00:00
17:00:00
18:00:00
19:00:00
20:00:00
21:00:00
22:00:00
23:00:00
24:00:00

But if the value comes over as "thisisastringvalue", i need to catch it...

nugs
ASKER CERTIFIED SOLUTION
Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
(remember to do a
using System.Text.RegularExpressions;
at the top of your file, or you have to say

System.Text.RegularExpressions.Regex.IsMatch(foo, "([0-1][0-9]|2[0-4]):00:00", RegexOptions.None)

instead :-)
Avatar of Nugs

ASKER

Thanks you very much, YOU ROCK!

Nugs