c# 和日期文化问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/614164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:18:07  来源:igfitidea点击:

c# and Date Culture Problems

c#.netasp.netdatetimecultureinfo

提问by TonyNeallon

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.

我编写了一个 asp.net 应用程序,我的一个回发例程只是将用户提交的表单数据保存到 sql 2005 db。一切都在我的开发机器上运行良好,但是当我部署到实时站点时,我从解析日期检查器中获取了无效日期。

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.

基本上它期望在现场机器上使用美国日期格式,但这不是我想要的。用户需要能够以 dd/MM/yyyy 格式输入。因此,像 21/10/2009 这样的有效日期会在实时服务器上返回错误,但不会在我的开发机器上返回。下面是抛出异常的代码。

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?

是否可以强制解析例程期望 dd/MM/yyyy 格式的日期?

采纳答案by sindre j

Do like this:

这样做:

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

回答by Matt Hamilton

You can use DateTime.ParseExactto specify an expected format.

您可以使用DateTime.ParseExact指定预期格式。

回答by Jakob Christensen

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

另一种选择是指定您希望在 web.config 文件中使用的文化:

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

回答by Paul Herzberg

Yes, ParseExact will do that as mentioned by Matt.

是的,ParseExact 会像马特提到的那样做到这一点。

The code would be something like:

代码类似于:

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