【问题标题】:DateTime Format Day of YearDateTime 格式 一年中的某一天
【发布时间】:2012-03-27 06:15:08
【问题描述】:

是否有 DateTime.ToString("") 的格式值以三位数字指定一年中的哪一天?

例如:

  • 2012 年 1 月 1 日将是 001
  • 2012 年 2 月 1 日是 032
  • 2012 年 12 月 31 日将是 366(闰年)
  • 2011 年 12 月 31 日将是 365

【问题讨论】:

    标签: c# datetime


    【解决方案1】:

    不,你可以使用DateTime.DayOfYear.ToString("000");

    你的例子:

    new DateTime(2012, 1, 1).DayOfYear.ToString("000");
    new DateTime(2012, 2, 1).DayOfYear.ToString("000");
    new DateTime(2012, 12, 31).DayOfYear.ToString("000");
    new DateTime(2011, 12, 31).DayOfYear.ToString("000");
    

    【讨论】:

      【解决方案2】:

      没有;那不是listed
      对不起。

      【讨论】:

        【解决方案3】:

        我需要一种方法来允许用户提供一种可以处理一年中某一天的格式,我想出了以下代码。

        public static string FormatDate(this DateTime date, string format)
        {
            var builder = new StringBuilder();
            int numOfjs = 0;
            bool escaped = false;
            foreach (char c in format)
            {
                if (c == 'j' && !escaped)
                {
                    numOfjs++;
                }
                else
                {
                    if (c == 'j' && escaped)
                    {
                        builder.Remove(builder.Length - 1, 1);
                    }
        
                    if (numOfjs > 0)
                    {
                        var dayOfYearFormat = new string('0', Math.Min(3, numOfjs));
                        builder.Append(date.DayOfYear.ToString(dayOfYearFormat));
                    }
        
                    numOfjs = 0;
                    builder.Append(c);
                }
        
                escaped = c == '\\' && !escaped;
            }
        
            if (numOfjs > 0)
            {
                var dayOfYearFormat = new string('0', Math.Min(3, numOfjs));
                builder.Append(date.DayOfYear.ToString(dayOfYearFormat));
            }
        
            return date.ToString(builder.ToString());
        }
        

        这允许您使用一种格式,将连续的未定界字母 j 替换为一年中的某一天。根据 j 的数量,它将补零最多 3 位数字。超过 3 个连续的 j 的行为就像只有 3 个。

        它基本上重写了格式,将分隔的 j 替换为 j,将连续的 j 替换为一年中的某一天。然后它将这种新格式传递给DateTime.ToString()

        【讨论】:

          【解决方案4】:

          我知道这有点老了,但如果你绝对,肯定地,必须在一行代码中完成,而不能访问 DateTime.DayOfYear 函数(就像我今天必须做的那样):

          int myDay = floor(Now() - Date(parseInt(Now().ToString("yyyy")), 1, 1)) + 1;
          

          【讨论】:

          • 我很好奇你的用例是什么,你 a) 必须在一行代码中完成,b) 没有 DayOfYear
          • 用户端脚本,MS Access 风格。是的,当然,我本可以加入并添加我们在编写脚本处理程序时甚至没有意识到存在的功能,但随后我们将不得不重新编译和测试并让客户获得新的构建并浪费更多的我们的大约十年来从未出现过的用例的时间和客户的时间 该程序已经出现了,但是如果我们可以使用已经提供的功能来完成它,那就更好了。
          猜你喜欢
          • 2015-04-27
          • 1970-01-01
          • 1970-01-01
          • 2013-03-25
          • 1970-01-01
          • 2020-07-26
          • 2016-01-01
          • 2016-01-22
          • 2014-08-03
          相关资源
          最近更新 更多