运行 .NET 8 控制台应用程序时,为什么MMM
当日期格式(例如 )的一部分时显示“June”而不是“Jun”,而当它本身时显示.ToString("dd-MMM-yy")
“Jun”(例如)?.ToString("MMM")
// Set culture to English (Australia)
var culture = new CultureInfo("en-AU");
// Get the current date
var currentDate = new DateTime(2024, 6, 8);
// Display the current date using the short date pattern
var formattedDate = currentDate.ToString("d", culture);
Console.WriteLine("Short date in en-AU culture: " + formattedDate); // Outputs: 8/06/2024
// Display the abbreviated month name separately
var abbreviatedMonth = currentDate.ToString("MMM", culture);
Console.WriteLine("Abbreviated month: " + abbreviatedMonth); // Outputs: Jun
var incorrect = currentDate.ToString("dd-MMM-yy", culture);
Console.WriteLine("Incorrect format: " + incorrect); // Outputs: 08-June-24
Windows 可以,但 C# 不行。请注意屏幕截图右下角的月份(我将 Windows 时间更改为六月)。
9
2 个回答
2
月份有两种缩写DateTimeFormatInfo
,一种叫,另一种叫。 June in AbbreviatedMonthNames
isJun
和 in AbbreviatedMonthGenitiveNames
it is的缩写June
。
文档中属格月份名称的解释如下:
在某些语言中,作为日期一部分的月份名称出现在所有格中。例如,ru-RU 或俄语(俄罗斯)文化中的日期由日数和属格月份名称组成,例如 1 Января(1 月 1 日)。
选择缩写的关键代码在这里:,其注释如下:
操作:检查格式,看看我们是否应该在格式中使用属格月份。从(format)字符串中的位置(index)开始,向后看并向前看是否有“d”或“dd”。在像“d MMMM”或“MMMM dd”这样的情况下,我们可以使用属格形式。如果有两个以上的“d”,则不使用属格形式。
所以如果格式中有d
或者的话,就会被选中。dd
June
|
正如DateTimeFormatInfo.AbbreviatedMonthNames
那样,该行为似乎起源于使用属性和的逻辑DateTimeFormatInfo.AbbreviatedMonthGenitiveNames
。
然而,尚未提供该问题的解决方案。
这两个属性有公共设置器。操作这些数组以使它们具有预期的内容可能非常容易。
// Set culture to English (Australia)
var culture = new CultureInfo("en-AU");
// Workaround for unexpected month abbreviations:
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames =
new string[] { "Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Aug", "Sep",
"Oct", "Nov", "Dec",
"" };
// Get the current date
var currentDate = new DateTime(2024, 6, 8);
// Display the current date using the short date pattern
var formattedDate = currentDate.ToString("d", culture);
Console.WriteLine("Short date in en-AU culture: " + formattedDate); // Outputs: 8/06/2024
// Display the abbreviated month name separately
var abbreviatedMonth = currentDate.ToString("MMM", culture);
Console.WriteLine("Abbreviated month: " + abbreviatedMonth); // Outputs: Jun
var fixedIncorrect = currentDate.ToString("dd-MMM-yy", culture);
Console.WriteLine("Fixed incorrect format: " + fixedIncorrect); // Outputs: 08-Jun-24 :-)
我不清楚为什么 .NET 的某些版本会为 en-AU 文化的这些月份缩写公开不同的值。在 .NET Framework 4.7.2 中,它默认工作正常。因此,新版本的 .NET 似乎确实存在问题,因为澳大利亚日期/时间格式设置政策本身不会在一夜之间发生变化。
2
-
1你不想直接分配吗
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames = culture.DateTimeFormat.AbbreviatedMonthNames;
?
–
-
3或者更好的是,您可以取消设置
UseGenitiveMonth
日期时间格式信息标志中的标志吗?
–
|
en_AU
确实是June
等等。–
.ToString("MMM", culture)
。大概在这种情况下它将使用独立形式,但独立形式对于 en_AU 是相同的。–
"MMM-yy"
评估为Jun-24
但"dd-MMM"
到08-June
。每当格式字符串包含日期部分时,MMM
计算结果为 ,June
否则为Jun
。如果它在某处包含日期部分,是否可以用作复杂格式字符串的指示符? ;o)–
08-Jun-24
。是为了说明问题吗?–
–
|