Puz Puz - 1 year ago 112
C# Question

How can I split date range into months

Now I get many date range data(DataTable) like this:

startDate: endDate:

2016-06-12 2016-08-13

2016-01-12 2016-03-13


How can I sum total days in each month in this year?
From January to November.

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)


Answer Source

Maybe something like this. I've written in it notepad so I'm not sure will it compile. Maybe you'll need a fix here and there. You can use a List to add dates from the for loop to the container, if you want.

        DateTime startDate = DateTime.Parse("2016-06-12");
        DateTime endDate = DateTime.Parse("2016-08-13");

        for(DateTime date = startDate, startDate <= endDate, date = date.AddMonths(1) )

And if you need only the month of particular date you can just ask it from that date via Month property.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download