1

should the following parsing works,

DateTime.ParseExact("20150105 91353", "yyyyMMdd Hmmss", CultureInfo.InvariantCulture);;

I found out the above doesnt work, while the below, works,

DateTime.ParseExact("20150105 091353", "yyyyMMdd HHmmss", CultureInfo.InvariantCulture);;

I would like to know what is wrong with the first line of code.

leppie
  • 115,091
  • 17
  • 196
  • 297
tesla1060
  • 2,621
  • 6
  • 31
  • 43

2 Answers2

1

According to MSDN

If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H".

This means this is correct DateTime.ParseExact("20150105 9:13:53", "yyyyMMdd H:mm:ss", CultureInfo.InvariantCulture); because it's using time separators

Pikoh
  • 7,582
  • 28
  • 53
1

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.

Ian
  • 30,182
  • 19
  • 69
  • 107