如何将日期范围划分为月份

本文关键字:划分 范围 日期 | 更新日期: 2023-09-27 18:17:06

现在我得到了许多日期范围数据(DataTable),像这样:

startDate可以:endDate:

2016-06-12 2016-08-13

2016-01-12 2016-03-13

如何计算这一年中每个月的总天数?从一月到十一月。

        DataTable dtDateRange = ds1.Tables[0];
        //Create Months
        int[] count = new int[12];
        //loop data
        for (int i = 0; i < dtDateRange.Rows.Count; i++)
        {
            DateTime startTime = ((DateTime)dtDateRange.Rows[i]["STARTDATE"]);
            DateTime endTime = ((DateTime)dtDateRange.Rows[i]["ENDDATE"]);
            for (int a = startTime.DayOfYear; a < endTime.DayOfYear; a++)
            {
                count[startTime.Month-1] = count[startTime.Month-1] + 1;
            }
        }
        foreach (int c in count)
        {
            Console.WriteLine(c);
        }
        Console.ReadKey();

如何将日期范围划分为月份

可能是这样的。我已经在记事本上写了,所以我不确定它是否能编译。也许你这里那里需要修理一下。如果需要,可以使用List将for循环中的日期添加到容器中。

        DateTime startDate = DateTime.Parse("2016-06-12");
        DateTime endDate = DateTime.Parse("2016-08-13");
        for(DateTime date = startDate, startDate <= endDate, date = date.AddMonths(1) )
            Console.WriteLine(date);

如果你只需要特定日期的月份,你可以通过month属性从该日期开始请求。

试试这个

           DateTime startDate1 = DateTime.Parse("2016-06-12");
            DateTime endDate1 = DateTime.Parse("2016-08-13");
            int days1 = endDate1.Subtract(startDate1).Days;
            DateTime startDate2 = DateTime.Parse("2016-01-12");
            DateTime endDate2 = DateTime.Parse("2016-03-13");
            int days2 = endDate1.Subtract(startDate1).Days;