在切换文化之间保存 DateTime.Now
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DateTime
不存储区域性信息。当您调用ToString
时,文化才变得重要。如果您想在返回之前使用特定区域性对其进行格式化,则需要将其作为字符串返回。也许您应该将其作为
DateTime
返回(并且您可能想使用DateTime.UtcNow
以便跨时区工作)并使用不变区域性对其进行格式化:CultureInfo.InvariantCulture
。The
DateTime
does not store culture information. It's when you callToString
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.Probably though you should return it as a
DateTime
(and you probably want to useDateTime.UtcNow
so that it works across timezones) and format it using the invariant culture:CultureInfo.InvariantCulture
.