Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormatException with TryParseExact

I want to format a typed in time to a specific standard:

private String CheckTime(String value)
{
    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" };
    DateTime expexteddate;
    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out expexteddate))
       return expexteddate.ToString("HH:mm");
    else
       throw new Exception(String.Format("Not valid time inserted, enter time like: {0}HHmm", Environment.NewLine));
}

When the user types it like: "09 00", "0900", "09:00", "9 00", "9:00"
But when the user types it like: "900" or "9" the system fails to format it, why? They are default formats I tought.

string str = CheckTime("09:00"); // works
str = CheckTime("900");          // FormatException at TryParseExact
like image 767
Cageman Avatar asked Oct 31 '22 22:10

Cageman


2 Answers

Hmm matches "0900" and H matches "09" you have to give 2 digits.

You can just change user input this way :

private String CheckTime(String value)
{
    // change user input into valid format
    if(System.Text.RegularExpressions.Regex.IsMatch(value, "(^\\d$)|(^\\d{3}$)"))
        value = "0"+value;

    String[] formats = { "HH mm", "HHmm", "HH:mm", "H mm", "Hmm", "H:mm", "H" };
    DateTime expexteddate;
    if (DateTime.TryParseExact(value, formats, System.Globalization.CultureInfo.InvariantCulture,     System.Globalization.DateTimeStyles.None, out expexteddate))
       return expexteddate.ToString("HH:mm");
    else
       throw new Exception(String.Format("Not valid time inserted, enter time like:     {0}HHmm", Environment.NewLine));
}
like image 96
Xeijp Avatar answered Nov 13 '22 21:11

Xeijp


string time = "900".PadLeft(4, '0');

Above line will take care, if value is 0900,900,9 or even 0 ;)

like image 37
Ambuj Avatar answered Nov 13 '22 21:11

Ambuj