5

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
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Cageman
  • 513
  • 3
  • 22
  • The H placeholder can match two digits as well, necessary to parse hours >= 10. So 900 matches Hmm with H = 90. Kaboom. – Hans Passant Jun 05 '14 at 10:18
  • @HansPassant: but `90` is `> 24`, so no need to treat the first two digits as hours. Is that a limitation of `TryParseExact`? I assume this is somehow related to my own question i've asked recently: http://stackoverflow.com/questions/21902722/datetime-parseexact-with-7-digits-one-or-two-digit-month – Tim Schmelter Jun 05 '14 at 10:21
  • First time I see this question, immediately @TimSchmelter [question](http://stackoverflow.com/q/21902722/447156) came to my mind as well.. In my opinion, parsing methods don't know what they do in such a cases.. – Soner Gönül Jun 05 '14 at 11:54

2 Answers2

1

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));
}
Xeijp
  • 853
  • 1
  • 7
  • 18
1

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

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

Ambuj
  • 433
  • 5
  • 10
  • This was also a posability to do. Up vote from me, but Xeijp answer fixed the problem for me at that time. – Cageman Aug 31 '17 at 07:31