Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# and Date Culture Problems

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?

like image 601
TonyNeallon Avatar asked Nov 30 '22 20:11

TonyNeallon


2 Answers

Do like this:

    System.Globalization.CultureInfo cultureinfo = 
        new System.Globalization.CultureInfo("en-gb");
    DateTime dt = DateTime.Parse("13/12/2009", cultureinfo);
like image 53
sindre j Avatar answered Dec 05 '22 19:12

sindre j


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

like image 41
Matt Hamilton Avatar answered Dec 05 '22 20:12

Matt Hamilton