民俗文化知道日期格式的.NET [英] Custom culture aware date format in .NET

查看:135
本文介绍了民俗文化知道日期格式的.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,大多数用于格式化日期时间值的标准字符串是文化的感知,例如ShortDatePattern(D)格式字符串转换年/月/日部分的顺序各地根据当前文化:

In .NET, most of the standard strings used for formatting a DateTime value are culture-aware, for example the ShortDatePattern ("d") format string switches the order of the year/month/day parts around depending on the current culture:

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)

我需要类似的一个日期格式只包含月份和日期的东西:

I need something similar for a date format containing only month and day:

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)

使用如在MM / DD自定义格式字符串不能正常工作;它会错误地在德国文化显示01.11的1月11日,当我希望它显示11.01。

Using e.g. the "MM/dd" custom format string doesn't work; it will incorrectly display "01.11" for Jan 11 in the German culture, when I want it to display "11.01."

如何建立一个自定义格式字符串,是以日期部分的顺序考虑?

How can I build a custom format string that takes the order of the date parts into account?

推荐答案

假如通过将有一个包含 M MM <一ShortDatePattern所有文化/ code>和 D DD 在某种分离的一些命令(我想不出例外公历,但我可能是错的),那么下面的工作:

Assuming all cultures passed will have a ShortDatePattern that contains M or MM and d or dd in some order with some sort of separator (I can't think of an exception for the Gregorian calendar, but I could be wrong) then the following will work:

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;
}

如果假设是很远的不匹配的,那么它就会恢复为 ShortDatePattern ,虽然它也可能最终只显示日期或仅一个月。

If the assumption is very far mis-matched, then it'll revert to ShortDatePattern, though it could also end up showing just the date or just the month.

这失败不是正确,包括在年底分离器或其他指标适当的时候。例如,原来的标准格式( YYYY-MM-DD )到 MM-DD ,而不是 - MM-DD ,这是月日的组合,没有年

It fails in not correctly including separators at the end or other indicators when appropriate. For example, it turns the standard format (yyyy-MM-dd) into MM-dd rather than --MM-dd, which is the standard format for month-day combinations with no year.

这篇关于民俗文化知道日期格式的.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆