Question

I've written a asp.net app and one of my postback routines simply saves user submitted form data to a sql 2005 db. All runs great on my development machine but when I deploy to the live site I'm getting invalid dates from my parse date checker.

Basically it is expecting an american date format on the live machine but this is not what I want. The user needs to be able to enter in dd/MM/yyyy format. So a valid date like 21/10/2009 returns errors on live server but not on my dev machine. Below is the code that throws the exception.

DateTime dt;
dt = DateTime.Parse(sdate);  
//sdate in GB dd/MM/yyyy format

Is it possible to force the parse routine to expect the date in dd/MM/yyyy format?

Was it helpful?

Solution

Do like this:

    System.Globalization.CultureInfo cultureinfo = 
        new System.Globalization.CultureInfo("en-gb");
    DateTime dt = DateTime.Parse("13/12/2009", cultureinfo);

OTHER TIPS

You can use DateTime.ParseExact to specify an expected format.

Another option is to specify the culture you wish to use in the web.config file:

<system.web>
    ...
    <globalization 
        culture="da-DK" 
        uiCulture="da-DK" requestEncoding="utf-8" responseEncoding="utf-8"
    />
</system.web>

Yes, ParseExact will do that as mentioned by Matt.

The code would be something like:

dt  = DateTime.ParseExact(sdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top