Reputation: 52047
I have a json string that contains the values for a datetime and a parsing mechanism that looks like this:
if (DateTime.TryParseExact(TheUserTimeString, "M.d.yyyy.HH.mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out TheUserTime))
{
TheObject.UserDateTime = TheUserTime;
}
The string TheUserTimeString is generated on the client. It can be 12.20.2011.13.21
and the code works fine but when it's 12.20.2011.13.2
the code breaks because the minutes are in one digit. And when the month is also in one digit... who knows.
What would be a better way to rewrite this parsing code so that the string gets parsed correctly every time.
Thanks for your suggestions.
Upvotes: 1
Views: 893
Reputation: 41767
Your DateTime format string just needs to be: "M.d.yyyy.H.m"
.
This allows for months, days, hours and minutes to be expressed as single digit values.
See here for the MSDN page documenting the valid formats of this string for further information.
Upvotes: 1