根据文档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