views:

65

answers:

3

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.

+5  A: 

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.

AndiDog
+1  A: 

The other computer is probably trying to parse the date as dd/MM/yyyy due to having a different region. You should be able to get it to parse if you enter the date as "2010-10-20"

Adam Ruth
Correct this is what i did and it works on both mine and client. Thanks.
acidzombie24
A: 

AntiDogs points to the exact cause of problem. But using ParseExact assures that you know the exact format and that client code adheres to this format.

In our system different clients due to bug requirements realisation sends to our server component DateTime values in two different cultures. I handle it using the following code:

private DateTime ParseWithDifferentCultures(string source)
{
    DateTime result;
    if (DateTime.TryParse(source, out result) 
        || DateTime.TryParse(source, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out result))
        return result;

    thrown new FormatException("Unrecognised DateTime format.");
}

Here, first we try to parse using current culture info, then using invariant culture info. Of course, it's not ideal but it suits our needs perfectly.

Dmitry Lobanov