c# and Date Culture Problems

扶醉桌前 提交于 2019-12-07 12:40:44

问题


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?


回答1:


Do like this:

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



回答2:


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




回答3:


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>



回答4:


Yes, ParseExact will do that as mentioned by Matt.

The code would be something like:

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


来源:https://stackoverflow.com/questions/614164/c-sharp-and-date-culture-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!