2

I have dates comming in a log file with the following format: "dMMyyHHmmss".

As I want to throw an exception if the format found is not exactly that one, I'm using DateTime.ParseExact. The thing is that I'm getting a FormatException with the following message:

'String '.....' was not recognized as a valid DateTime.

The code to emulate this is:

var format = "dMMyyHHmmss";

var date = new DateTime(2018, 1, 1, 1, 1, 1);
var strDate = date.ToString(format);
date = DateTime.ParseExact(strDate, format, CultureInfo.InvariantCulture);

Any thoughts why I can't use that format?

joacoleza
  • 775
  • 1
  • 9
  • 26
  • 3
    Its pretty obvious isnt it? If you would have used the debugger you would see that the `srtDate` variable is: `"10118010101"`. Using `dMM` means a single digit day and a double digit (padded) month, so is it `10/11`? or `1/01`? Its ambiguous, this is why you need delimiters – maccettura Aug 28 '18 at 20:36

1 Answers1

5

That's because the format somewhat ambiguous to the LL parser.

The string you got is 10118010101

The parser reads 1 and goes like, ok its a 1 for d
Then it reads 0 and its confused, should it be 10 for d or should it be 1 for d and 01 for MM?

You can make the parser happy if you add a delimiter in between or use dd instead of d to make the grammar unambiguous

Steve
  • 11,696
  • 7
  • 43
  • 81