根據文檔Formatting Date and Time for a Specific CultureDateTime格式和區域性
的
DateTime
結構提供,讓您的應用程序在一個DateTime類型進行區分區域性的操作方法。一個應用程序可以使用DateTimeFormatInfo
類來格式化並顯示基於培養物的DateTime類型。例如,使用DateTimeFormatInfo.ShortDatePattern
,日期2001年2月1日,可以格式化爲2001年2月1日爲英語(美國),「EN-US」,英語(英國)文化和01/02/2001, 「en-GB」,文化。一個
DateTimeFormatInfo
對象可以爲特定培養或用於不變培養被創建,而不是爲中性培養。 中性文化沒有提供足夠的信息,以顯示正確的日期格式。,則拋出異常,如果應用程序試圖創建使用中性培養一個DateTimeFormatInfo
對象。
但是怎麼來的以下不拋出異常?它在哪裏獲得關於如何格式化日期的信息,因爲沒有指定特定的文化?
Console.WriteLine(DateTime.Now.ToString("d", new CultureInfo("fr")));
更新:
您可以創建例如new CultureInfo("fr-FR")
或new CultureInfo("fr")
特定文化或中性文化, 的實例。
在DateTime.ToString
方法,它說
了toString(String)方法返回在使用當前區域性的格式約定特定格式的日期和時間值的字符串表示;有關更多信息,請參閱
CultureInfo.CurrentCulture
。
而且CultureInfo文件說
由該屬性及其相關對象返回的CultureInfo對象確定日期,時間,數字,貨幣值,文字的排序順序,外殼的默認格式約定和字符串比較。
更新2
是的,所以上面提到的MSDN頁面是過時的和框架的行爲發生了變化。
我有以下代碼
var culture = new CultureInfo("en");
Console.WriteLine(DateTime.Now.ToString("d", culture));
當我運行這段代碼針對.NET 3.0我得到下面的異常。但它在.NET 4.6.2上運行良好。
An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: Culture 'en' is a neutral culture. It cannot be used in formatting and parsing and therefore cannot be set as the thread's current culture.
所以,回到我原來的問題。當我使用中性文化時,關於DateTime
格式的信息從何而來?
如果您還沒有指定具體的文化比你能告訴我什麼是'新的CultureInfo(「FR」)'??? –
'新CultureInfo(「fr」)' – Pikoh
文化可以是中性的或特定的。例如,'en-US'或'fr-FR'是特定的文化,而'en'和'fr'是中性文化,並沒有提供關於如何格式化日期,數字等的足夠信息。參見https: //msdn.microsoft.com/en-us/library/ff647353.aspx獲取更多信息。 – erdinger