.NET中的自定义文化感知日期格式

mat*_*atk 7 .net c# datetime

在.NET中,用于格式化DateTime值的大多数标准字符串都是文化感知的,例如ShortDatePattern("d")格式字符串根据当前文化切换年/月/日部分的顺序:

6/15/2009 1:45:30 PM -> 6/15/2009 (en-US)
6/15/2009 1:45:30 PM -> 15/06/2009 (fr-FR)
6/15/2009 1:45:30 PM -> 15.06.2009 (de-DE)
Run Code Online (Sandbox Code Playgroud)

对于仅包含月和日的日期格式,我需要类似的东西:

6/15/2009 1:45:30 PM -> 6/15 (en-US)
6/15/2009 1:45:30 PM -> 15/06 (fr-FR)
6/15/2009 1:45:30 PM -> 15.06. (de-DE)
Run Code Online (Sandbox Code Playgroud)

使用例如"MM/dd"自定义格式字符串不起作用; 当我希望它显示"11.01"时,它将在1月11日在德国文化中错误地显示"01.11".

如何构建一个自定义格式字符串,将日期部分的顺序考虑在内?

Jon*_*nna 2

假设传递的所有文化都有一个 ShortDatePattern,其中包含MorMMdordd以某种顺序带有某种分隔符(我想不出公历的例外,但我可能是错的),那么以下内容将起作用:

private static string FindMonthDayOnly(System.Globalization.CultureInfo ci)
{
  string shortPattern = ci.DateTimeFormat.ShortDatePattern;
  while(shortPattern[0] != 'd' && shortPattern[0] != 'M')
  {
    shortPattern = shortPattern.Substring(1);
    if(shortPattern.Length == 0)
      return ci.DateTimeFormat.ShortDatePattern;
  }
  while(shortPattern[shortPattern.Length - 1] != 'd' && shortPattern[shortPattern.Length - 1] != 'M')
  {
    shortPattern = shortPattern.Substring(0, shortPattern.Length - 1);
    if(shortPattern.Length == 0)
      return ci.DateTimeFormat.ShortDatePattern;
  }
  return shortPattern;
}
Run Code Online (Sandbox Code Playgroud)

如果假设非常不匹配,那么它将恢复为ShortDatePattern,尽管它最终也可能只显示日期或月份。

它未能正确地在末尾包含分隔符或在适当时包含其他指示符。例如,它将标准格式 ( yyyy-MM-dd) 转换为,MM-dd而不是--MM-dd,这是没有年份的月日组合的标准格式。