Reputation: 523
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
Upvotes: 5
Views: 582
Reputation: 453
string time = "900".PadLeft(4, '0');
Above line will take care, if value is 0900,900,9 or even 0 ;)
Upvotes: 1
Reputation: 873
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));
}
Upvotes: 1