Search code examples
datetime.net-3.5formatexception

Weird DateTime.Parse exception in 3.5?


This line of code works on my computer (64-bit Win7). I tested on XP 32bits in a VM. It works fine.

static bool HasExpire { get { return DateTime.Now >= DateTime.Parse("10/20/2010"); } }

However on a client machine it throws this exception:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

[FormatException: String was not recognized as a valid DateTime.]
   System.DateTimeParse.Parse(String s,
       DateTimeFormatInfo dtfi,
       DateTimeStyles styles) +2838082

Why can't it parse the date on the client machine when it does on my VM? The date is hardcoded in. I don't understand how this can be happening. I confirmed the client has 3.5 and if I change that line to return false always, the app runs perfectly fine except it can't tell when the trial expired.


Solution

  • DateTime.Parse may unexpectedly throw FormatException because it is locale-dependent. From the MSDN page:

    Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel.

    You may rather want to use DateTime.ParseExact.