How to check if a string value is in a correct time format?
If you didn't want to write methods, you could always check and see if converts successfully. If needed you can use a bool to show whether or not it was valid.
bool passed = false;
string s = String.Empty;
DateTime dt;
try{
s = input; //Whatever you are getting the time from
dt = Convert.ToDateTime(s);
s = dt.ToString("HH:mm"); //if you want 12 hour time ToString("hh:mm")
passed = true;
}
catch(Exception ex)
{
}
You can use TimeSpan.Parse
or TimeSpan.TryParse
methods for that.
These methods uses this format.
[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
Elements between in square brackets ([
and ]
) are optional.
TimeSpan.Parse("12:33:25") // Parsing fine
TimeSpan.Parse("03:04:05") // Parsing fine
TimeSpan.Parse("3:4:5") // Parsing fine
TimeSpan.Parse("25:60:60") // Throws overflow exception.
Additional method can be written for the purpose of the string time format validation. TimeSpan
structure has got TryParse
method which will try to parse a string as TimeSpan
and return the outcome of parsing (whether it succeeded or not).
Normal method:
public bool IsValidTimeFormat(string input)
{
TimeSpan dummyOutput;
return TimeSpan.TryParse(input, out dummyOutput);
}
Extension method (must be in separate non-generic static class):
public static class DateTimeExtensions
{
public static bool IsValidTimeFormat(this string input)
{
TimeSpan dummyOutput;
return TimeSpan.TryParse(input, out dummyOutput);
}
}
Calling the methods for the existing string input;
(lets imagine it's initialized with some value).
Normal method:
var isValid = IsValidTimeFormat(input);
Extension method:
var isValid = DateTimeExtensions.IsValidTimeFormat(input);
or
var isValid = input.IsValidTimeFormat();
UPDATE: .NET Framework 4.7
Since the release of .NET Framework 4.7, it can be written a little bit cleaner because output parameters can now be declared within a method call. Method calls remain the same as before.
Normal method:
public bool IsValidTimeFormat(string input)
{
return TimeSpan.TryParse(input, out var dummyOutput);
}
Extension method (must be in separate non-generic static class):
public static class DateTimeExtensions
{
public static bool IsValidTimeFormat(this string input)
{
return TimeSpan.TryParse(input, out var dummyOutput);
}
}