在切换文化之间保存 DateTime.Now

发布于 2024-12-11 10:55:41 字数 780 浏览 0 评论 0原文

我有一个 ASP.NET MVC 应用程序。它是多语言的,并在 cookie 中写入一些值。如果应用程序的当前文化(语言)和 cookie 中存储的 DateTime 值具有不同的格式,则会出现此问题。因此,我决定仅在英语文化中存储和检索日期时间值。但我遇到了麻烦。

 var currentCulture = Thread.CurrentThread.CurrentCulture; //for example, ru-RU
 var currentUICulture = Thread.CurrentThread.CurrentUICulture;

 var englishCulture = CultureInfo.GetCultureInfo("en-US");
 Thread.CurrentThread.CurrentCulture = englishCulture;
 Thread.CurrentThread.CurrentUICulture = englishCulture;

 var dateTime = DateTime.Now;  //  10/22/2011 9:56:15 AM (in English)


 Thread.CurrentThread.CurrentCulture = currentCulture;
 Thread.CurrentThread.CurrentUICulture = currentUICulture;

 return dateTime;              //   22.10.2011 9:56:15 (in Russian). But why?

我想以英语文化返回 DateTime.Now 。

I have an asp.net mvc application. It's multilanguages and writes some values in cookie. The problem occurs if the currentCulture (language) of application and the value of DateTime stored in cookie has different formats. Therefore I've decided to store and retrieve DateTime values only in English culture. But I've faced with the trouble.

 var currentCulture = Thread.CurrentThread.CurrentCulture; //for example, ru-RU
 var currentUICulture = Thread.CurrentThread.CurrentUICulture;

 var englishCulture = CultureInfo.GetCultureInfo("en-US");
 Thread.CurrentThread.CurrentCulture = englishCulture;
 Thread.CurrentThread.CurrentUICulture = englishCulture;

 var dateTime = DateTime.Now;  //  10/22/2011 9:56:15 AM (in English)


 Thread.CurrentThread.CurrentCulture = currentCulture;
 Thread.CurrentThread.CurrentUICulture = currentUICulture;

 return dateTime;              //   22.10.2011 9:56:15 (in Russian). But why?

I want to return DateTime.Now in English culture.

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

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

发布评论

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

评论(1

笑忘罢 2024-12-18 10:55:41

DateTime 不存储区域性信息。当您调用 ToString 时,文化才变得重要。如果您想在返回之前使用特定区域性对其进行格式化,则需要将其作为字符串返回。

return DateTime.Now.ToString(cultureInfo);

也许您应该将其作为 DateTime 返回(并且您可能想使用 DateTime.UtcNow 以便跨时区工作)并使用不变区域性对其进行格式化:CultureInfo.InvariantCulture

The DateTime does not store culture information. It's when you call ToString that the culture matters. If you want to format it with a specific culture before returning it, you need to return it as a string.

return DateTime.Now.ToString(cultureInfo);

Probably though you should return it as a DateTime (and you probably want to use DateTime.UtcNow so that it works across timezones) and format it using the invariant culture: CultureInfo.InvariantCulture.

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