获取两个日期之间的所有日期,月份,年份C#

时间:2015-11-13 09:39:05

标签: c# .net arrays datetime

我是C#的初学者,我有两个DateTime,例如:

startday=27/10/2014
enddate=15/02/2015

我想要输出的函数是一个像:

这样的数组
 [
        [0=>2014
         1=>10
          2=>4( 4 is number of date in October)
        ]

         [0=>2014
          1=>11
          2=>30 (30 is number of day in November)
        ]
        ....
        [0=>2015
          1=>2
          2=>15(15 is number of day in February)
        ]
   ]

请帮助我,谢谢

1 个答案:

答案 0 :(得分:1)

你可以做一些事情:

void Main()
{
    var start = new DateTime(2014, 10, 27);
    var end = new DateTime(2015, 02, 15);

    var daysPerMonth = new Dictionary<string, int>();

    var currentMonth = new DateTime(start.Year, start.Month, 1);
    while (true)
    {
        // Handle start and end in same month.
        if (start.ToString("MMyyyy") == currentMonth.ToString("MMyyyy") && end.ToString("MMyyyy") == currentMonth.ToString("MMyyyy"))
        {
            daysPerMonth.Add(currentMonth.ToString("MMyyyy"), end.Day - start.Day);
            break;
        }

        // Handle last month. 
        if (currentMonth.ToString("MMyyyy") == end.ToString("MMyyyy"))
        {
            daysPerMonth.Add(currentMonth.ToString("MMyyyy"), DateTime.DaysInMonth(end.Year, end.Month) - end.Day);
            break;
        }

        // Handle first month.
        if (currentMonth.ToString("MMyyyy") == start.ToString("MMyyyy"))
        {
            daysPerMonth.Add(currentMonth.ToString("MMyyyy"), DateTime.DaysInMonth(start.Year, start.Month) - start.Day);
        }
        // Handle full month.
        else
        {
            daysPerMonth.Add(currentMonth.ToString("MMyyyy"), DateTime.DaysInMonth(currentMonth.Year, currentMonth.Month));
        }
        currentMonth = currentMonth.AddMonths(1);
    }
    // daysPerMonth: 
    // {
    //    { "102014", 4 },
    //    { "112014", 30 },
    //    { "122014", 31 },
    //    { "012015", 31 },
    //    { "022015", 13 }
    // }
}