Jules
Jules

Reputation: 587

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

Upvotes: 11

Views: 28030

Answers (5)

gabegi
gabegi

Reputation: 19

How I solved it using TryParseExact

// Ask user to provide time

Console.WriteLine("Please enter a time in the format HH:MM");

string timeInput = Console.ReadLine();

// Indicate the time format you want

  string timeFormat = "HH:mm";
  CultureInfo culture = new CultureInfo("jp-JP");

// Check if it matches

  if(DateTime.TryParseExact(timeInput, timeFormat, culture, 
  DateTimeStyles.None, out DateTime result) == true)

  {

   Console.WriteLine("You got it");

   };

Check this post for more details https://social.msdn.microsoft.com/Forums/en-US/a72bb508-e35e-4632-b74a-efb6df04c4ab/c-check-if-time-from-textbox-is-a-valid-time?forum=aspgettingstarted

Upvotes: 0

rostamiani
rostamiani

Reputation: 3265

Timespan is a piece of time not a valid time of the day. it accepts "300" as "300:00:00" but it's not want.

This works for you

bool IsTime(string myValue) {

    bool Succeed = true;

    try {
        DateTime temp = Convert.ToDateTime(myValue);
    }
    catch (Exception ex) {
        Succeed = false;
    }

    return Succeed;
}

Upvotes: 1

Iggils
Iggils

Reputation: 21

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)
{

}

Upvotes: 2

msmolcic
msmolcic

Reputation: 6577

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);
    }
}

Upvotes: 25

Soner Gönül
Soner Gönül

Reputation: 98868

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.

Upvotes: 3

Related Questions