Is there a possibility to check wether a string is in a valid time format or not?
Examples:
12:33:25 --> valid
03:04:05 --> valid
3:4:5 --> valid
25:60:60 --> invalid
You can use TimeSpan.
It should start from 0-23 or 00-23. It should be followed by a ':'(colon). It should be followed by two digits from 00 to 59. It should not end with 'am', 'pm' or 'AM', 'PM'.
Full date/time pattern (short time). More information: The full date short time ("f") format specifier.
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);
}
}
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.
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With