C # and date culture issues

I wrote an asp.net application and one of my postback procedures simply saves the user submitted data in sql 2005 db. Everything works fine on my development machine, but when I deploy to the site, I get invalid dates from my parsing date check.

In principle, he expects the format of the American version on a real computer, but this is not what I want. The user should be able to enter the dd / MM / yyyy format. Thus, a valid date, such as 10/21/2009, returns errors on a real 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 parsing procedure to expect a date in the format dd / MM / yyyy?

+4
source share
4 answers

Do the following:

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

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

+6
source

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

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

Yes, ParseExact will do this as Matt indicated.

The code will look something like this:

 dt = DateTime.ParseExact(sdate, "dd/MM/yyyy", CultureInfo.InvariantCulture); 
+2
source

All Articles