Tuesday 20 November 2012

DateTime.ParseExact can be misleading

Last night, I was made aware of a crash in our Payslips for PAYE Tools program that occured pretty much every time it ran.

It turns out the user had changed the short date format on their system, so it included either a . or a – as the separator.

I had this line in my code:

Date = DateTime.ParseExact(value, "dd/MM/yyyy", null);

While this looks like it might do the right thing, it turns out it doesn’t as I didn’t use the invariant culture for the conversion.  The word exact is a bit misleading, as I’d assumed (incorrectly) that / was a character.  In fact, it’s replaced with the date separator, and no longer matches the string that came out of the database with a /

No comments:

Post a Comment