Jules Jules - 1 year ago 67
C# Question

How to check if a string value is in a correct time format?

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

Answer Source

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);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download