问题
I'm trying to set LongTimePattern property of CurrentCulture with the following code:
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern = "HH:mm:ss";
and I'm getting InvalidOperationException: Instance is read-only.
Any idea how can I change it? I want to force LongTimePattern to show 24h format for any culture.
回答1:
If you change the System.Threading.Thread.CurrentThread.CurrentCulture then it will automatically update the LongTimePattern.
You can't make any updation in current assigned culture info but create a new one and assign it to current culture.
System.Globalization.CultureInfo c = new System.Globalization.CultureInfo("es-ES");
c.DateTimeFormat.LongTimePattern = "h-mm-ss";
Thread.CurrentThread.CurrentCulture = c;
回答2:
If you just want to change ONE or TWO values and keep the rest the same, you can use Clone to get a writable copy of the current culture, eg:
CultureInfo i;
i = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
i.DateTimeFormat.LongTimePattern = "HH:mm:ss";
i.DateTimeFormat.ShortTimePattern = "HH:mm";
Thread.CurrentThread.CurrentCulture = i;
i = (CultureInfo)Thread.CurrentThread.CurrentUICulture.Clone();
i.DateTimeFormat.LongTimePattern = "HH:mm:ss";
i.DateTimeFormat.ShortTimePattern = "HH:mm";
Thread.CurrentThread.CurrentUICulture = i;
This seems better than having to use a culture string to get your starting culture.
回答3:
I'm not sure if you can change the cultures, allowing you to do so would defeat the purpose of having cultures in the first place - they should show the date and time in the commonly accepted format used by that culture.
If you wish to show a different format, then you can always use a custom date/time formatter.
See http://msdn.microsoft.com/en-us/library/az4se3k1.aspx for all available pre-set formats, and details on how to display your own format.
来源:https://stackoverflow.com/questions/10332064/currentculture-datetimeformat-longtimepattern-read-only