我提出这篇文章的原因与提问者完全相同。然而,在测试解决方案时,我通过不同的文化提出了问题。
只是想分享我的最终解决方案,它适用于 .Net 中的所有中立文化:
private static string GetPatternWithoutYear(string pattern)
{
if (pattern.EndsWith("yyyy"))
pattern = pattern.Substring(0, pattern.Length - 5);
else if (pattern.StartsWith("yyyy"))
pattern = pattern.Substring(5);
// some even end with yyyy.
else if (pattern.EndsWith("yyyy."))
pattern = pattern.Substring(0, pattern.Length - 5);
else if (pattern.EndsWith("yy"))
pattern = pattern.Substring(0, pattern.Length - 3);
// and some seldom with yy.
else if (pattern.EndsWith("yy."))
pattern = pattern.Substring(0, pattern.Length - 3);
// bul
else if (pattern.EndsWith("yyyy 'г.'"))
pattern = pattern.Substring(0, pattern.Length - 9);
// tuk
else if (pattern.EndsWith(".yy 'ý.'"))
pattern = pattern.Substring(0, pattern.Length - 8);
return pattern;
}
使用以下测试(我不会粘贴结果,因为它太长了):
var cultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures);
foreach (var culture in cultures)
{
string pattern = culture.DateTimeFormat.ShortDatePattern;
pattern = GetPatternWithoutYear(pattern);
Console.WriteLine($"{culture.ThreeLetterISOLanguageName}: {culture.DateTimeFormat.ShortDatePattern.PadRight(12)} {pattern.PadRight(8)} {DateTime.Now.ToString(pattern)}");
}
第一行结果:
ivl: MM/dd/yyyy MM/dd 03.05
aar: dd/MM/yyyy dd/MM 05.03
afr: yyyy-MM-dd MM-dd 03-05
agq: d/M/yyyy d/M 5.3
aka: yyyy/MM/dd MM/dd 03.05
amh: dd/MM/yyyy dd/MM 05.03
ara: dd/MM/yy dd/MM 05.03
arn: dd-MM-yyyy dd-MM 05-03
asm: dd-MM-yyyy dd-MM 05-03
asa: dd/MM/yyyy dd/MM 05.03
ast: d/M/yyyy d/M 5.3
aze: dd.MM.yyyy dd.MM 05.03
aze: dd.MM.yyyy dd.MM 05.03
aze: dd.MM.yyyy dd.MM 05.03
bak: dd.MM.yy dd.MM 05.03
...