简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM