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

本文关键字:日期 年份 之间 月份 两个 获取 | 更新日期: 2023-09-27 18:21:50

我是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)
        ]
   ]

请帮帮我,谢谢

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

您可以按照以下方式进行操作:

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