DateTime格式和中性文化

时间:2017-05-24 14:46:35

标签: c# .net globalization

根据文件Formatting Date and Time for a Specific Culture

  

DateTime结构提供的方法允许应用程序对DateTime类型执行区分大小写的操作。应用程序可以使用DateTimeFormatInfo类来格式化并显示基于区域性的DateTime类型。例如,使用DateTimeFormatInfo.ShortDatePattern,2001年2月1日的日期可以格式化为英语(美国)的2/1/2001," en-US",culture和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格式的信息来自哪里?

1 个答案:

答案 0 :(得分:2)

来自the most recent version of the MSDN doc on DateTimeFormatInfo

  

但是,中性文化缺少特定于文化的格式信息,因为它独立于特定国家/地区。 .NET Framework不返回使用通用值填充DateTimeFormatInfo对象,而是返回DateTimeFormatInfo对象,该对象反映特定区域性文化的格式约定。例如,DateTimeFormatInfo对象中性文化反映了en-US文化的格式约定,fr文化的DateTimeFormatInfo对象反映了fr-FR文化的格式约定。

这也在.NET 4的What's New in Globalization and Localization文章中描述:

  

如果应用程序试图访问中性文化属性(如DateTimeFormatInfo.FirstDayOfWeek),则.NET Framework的早期版本会引发异常。 在.NET Framework 4中,中性文化属性返回的值反映了对该中性文化最主要的特定文化。例如,法语中性语言环境从法语中检索其大多数属性的值(法国)。 FirstDayOfWeek属性返回DayOfWeek.Monday,它反映了该属性在法国(法国)文化中的价值。

相关问题