Reputation: 199
Why this code is receiving error for input like "8:16AM":
string time = Console.ReadLine();
DateTime outValue = DateTime.MinValue;
bool error = DateTime.TryParseExact(time, "HH:mmtt" /*"hh:mmtt"*/, CultureInfo.InvariantCulture, DateTimeStyles.None, out outValue);
Console.WriteLine(error);
Console.WriteLine(outValue);
Console.Read();
What should I set in order to accept such an input "8:16" and convert it to DateTime object ?
Upvotes: 0
Views: 60
Reputation: 419
This happends because you write HH:mmtt. Try this:
bool error = DateTime.TryParseExact(time, "H:mm:tt" /*"h:mm:tt"*/,
CultureInfo.InvariantCulture, DateTimeStyles.None, out outValue);
Upvotes: 1
Reputation: 7847
It's caused by expecting two digits for hours.
You can add leading zero if it's missing.
string time = Console.ReadLine();
DateTime outValue = DateTime.MinValue;
if (time.Length == 6)
time = "0" + time;
bool error = DateTime.TryParseExact(time, "HH:mmtt" /*"hh:mmtt"*/, CultureInfo.InvariantCulture, DateTimeStyles.None, out outValue);
Console.WriteLine(error);
Console.WriteLine(outValue);
Console.Read();
But it's better to go with H:mmtt
template as pointed by Jamiec
Upvotes: 1
Reputation: 136154
You've used HH
which expects a 2 digit hour. You can either pass 08:16AM
or change your HH
to H
.
Live example: http://rextester.com/IPNS3820
Upvotes: 5