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.
The
DateTimedoes not store culture information. It’s when you callToStringthat 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.UtcNowso that it works across timezones) and format it using the invariant culture:CultureInfo.InvariantCulture.