在测试项目中设置 CultureInfo?

发布于 2024-08-19 20:05:11 字数 560 浏览 4 评论 0原文

我有一个 MVC 应用程序,我已在 web.config 中设置了全球化。网络应用程序一切顺利。但在我的测试项目中,我的服务层遇到了问题。我要求提供以下格式的出生日期:dd/MM/yyyy。我将其作为字符串传递到我的服务层。我有一个正则表达式来检查它的格式是否正确,但是当它是正确的并且我尝试将其转换为日期时,我收到了错误。这是因为 CultureInfo 设置为 en.US,我希望它为 en.GB。我已经尝试在我的初始化测试方法之一中执行以下操作,但无济于事:

string sCulture = ConfigurationSettings.AppSettings["CultureToUse"];  //returns "en.GB"
        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(sCulture);
        CultureInfo.CreateSpecificCulture(sCulture);

有什么想法如何在我的测试项目中设置 CultureInfo 吗?

I've got an MVC app that I've set the globalization in the web.config. All is well in the web app. But in my tests project I'm getting an issue in my service layer. I'm asking for date of birth in the following format dd/MM/yyyy. I'm passing this as a string to my service layer. I've got a RegEx to check that it is formatted correctly but when it is and I try to convert it to a date I'm getting an error. This is because the CultureInfo is set to en.US, I want it to be en.GB. I've tried in one of my initialise test methods to do the following, to no avail:

string sCulture = ConfigurationSettings.AppSettings["CultureToUse"];  //returns "en.GB"
        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(sCulture);
        CultureInfo.CreateSpecificCulture(sCulture);

Any ideas how to set CultureInfo in my tests project?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜中书 2024-08-26 20:05:11

由于您强制执行数据的格式并且它只是数字,因此您不应依赖用户定义的设置,最好使用 DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture)。

CurrentUICulture 属性控制为应用程序加载的资源。 CurrentCulture 是您想要设置/获取的内容来控制解析/格式化。

Since you enforce the format that the data is in and it only is numeric, you shouldn't rely on a user defined setting and are better off using DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture).

The CurrentUICulture property controls the resources that get loaded for the app. CurrentCulture is what you want to set/get to control parsing/formatting.

不打扰别人 2024-08-26 20:05:11
ConfigurationSettings.AppSettings["CultureToUse"]

必须返回“en-GB”而不是“en.GB”,希望这有帮助!

ConfigurationSettings.AppSettings["CultureToUse"]

Must return "en-GB" not "en.GB", hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文