This is one of the special cases where Custom DateTime
format might find the input ambiguous.
When you do not have separator between hour and minutes, the single H
format cannot distinguish the second number belongs to the hour or the minutes, thus your parse failed.
91353 //interpreted either as 9 13 53 or 91 35 3 - which one? ambiguous -> error
But this is ok:
string str = "20150105 9:13:53"; //no ambiguity with format yyyyMMdd H:mm:ss
string fmt = "yyyyMMdd H:mm:ss"; //can handle both "20150105 9:13:53" and "20150105 09:13:53"
DateTime dt = DateTime.ParseExact(str, fmt, CultureInfo.InvariantCulture);
To solve it, try to do little manipulation on your original string
.
string dtstr = "20150105 91353";
string fmt = "yyyyMMdd Hmmss";
string[] parts = dtstr.Split(' ');
string str = parts[1].Length < 6 ? string.Join(" 0", parts) : dtstr;
DateTime dt = DateTime.ParseExact(str, fmt, CultureInfo.InvariantCulture);
Then it should be OK.