How can I check if a string value is in the correct time format?
An additional method can be written to check the format of the string time. The structure TimeSpan
has a method TryParse
that will try TimeSpan
to parse the string like and return the parse result (success or failure).
The usual method:
public bool IsValidTimeFormat(string input)
{
TimeSpan dummyOutput;
return TimeSpan.TryParse(input, out dummyOutput);
}
Extension method (must be in a separate, non-equivalent static class):
public static class DateTimeExtensions
{
public static bool IsValidTimeFormat(this string input)
{
TimeSpan dummyOutput;
return TimeSpan.TryParse(input, out dummyOutput);
}
}
Calling methods on an existing one string input;
(assuming it is initialized with some value).
The usual method:
var isValid = IsValidTimeFormat(input);
Extension method:
var isValid = DateTimeExtensions.IsValidTimeFormat(input);
or
var isValid = input.IsValidTimeFormat();
UPDATE: .NET Framework 4.7
As of the release of the .NET Framework 4.7, it can be written a little cleaner because output parameters can now be declared in a method call. The method call remains the same as before.
The usual method:
public bool IsValidTimeFormat(string input)
{
return TimeSpan.TryParse(input, out var dummyOutput);
}
Extension method (must be in a separate, non-equivalent static class):
public static class DateTimeExtensions
{
public static bool IsValidTimeFormat(this string input)
{
return TimeSpan.TryParse(input, out var dummyOutput);
}
}
source to share
You can use TimeSpan.Parse
or TimeSpan.TryParse
for this.
These methods use this format.
[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
Items between 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.
source to share
If you don't want to write methods, you can always check and check if the conversions are successful. If necessary, you can use bool to show if it really happened.
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)
{
}
source to share