15,942,710 members
See more:
I have following Dates as parameters

Start Date: 02/15/2016
End Date: 02/14/2017

Expected Output:

MonthStart MonthEnd NoOfDays
02/15/2016 02/29/2016 15
03/01/2016 03/31/2016 31
04/01/2016 04/30/2016 30
05/01/2016 05/31/2016 31
06/01/2016 06/30/2016 30
07/01/2016 07/31/2016 31
08/01/2016 08/31/2016 31
09/01/2016 09/30/2016 30
10/01/2016 10/31/2016 31
11/01/2016 11/30/2016 30
12/01/2016 12/31/2016 31
01/01/2017 01/31/2017 31
02/01/2017 02/14/2017 14

What I have tried:

I am new to this need help in getting above expected output.
Posted
Updated 25-Dec-22 8:19am
Tomas Takac 20-Mar-16 10:30am
What have you tried? Where are you stuck?

## Solution 2

Try this..
C#
```public static void PrintDates(DateTime start, DateTime end)
{
while (start < end)
{
var lastDayOfMonth = DateTime.DaysInMonth(start.Year, start.Month);
var howManyDays = lastDayOfMonth - start.Day;
if(end<=monthEndDate)
Console.WriteLine("{0} {1} {2}", start.ToShortDateString(), end.ToShortDateString(), (end - start).TotalDays + 1);
else
Console.WriteLine("{0} {1} {2}", start.ToShortDateString(), monthEndDate.ToShortDateString(), (monthEndDate - start).TotalDays + 1);
}
}```

C#
```var start = new DateTime(2016, 02, 15);
var end = new DateTime(2017, 02, 14);
PrintDates(start, end);
```

skmar100 20-Mar-16 12:31pm
Thank you very much for the help.
jinesh sam 20-Mar-16 13:00pm
You're welcome! :)

## Solution 1

Get familiar with date maths using DateTime.Add etc, and the TimeSpan class. For any given month you can find the start by making a DateTime class that has 1 as the day and the given month and year. To find out when that month ends simply add one month to the first of the month then subtract one day (add -1 days).

That gives you the start and end date so go through each day and use DateTime.DayOfWeek[^] to see if it is a week day, and if it is add 1 to a running count. If you make that into a function you just need to run it for each month between the start and end dates.

## Solution 3

I made an small change on jinesh sam solution as it was looping for ever.
On the if (endDate <= monthEndDate) you need to add startDate = startDate.AddDays(daysInMonth); to stop looping.
Thanks for the script Jinesh it saves me a lot of time for my project!

```var startDate = new DateTime(2022, 01, 01);
var endDate = new DateTime(2022, 12, 31);

while (startDate < endDate)
{
var lastDayOfMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);

var daysInMonth = lastDayOfMonth - startDate.Day;

if (endDate <= monthEndDate)
{
Console.WriteLine("{0} {1} {2}", startDate.ToShortDateString(), endDate.ToShortDateString(), (endDate - startDate).TotalDays + 1);
}
else
{
Console.WriteLine("{0} {1} {2}", startDate.ToShortDateString(), monthEndDate.ToShortDateString(), (monthEndDate - startDate).TotalDays + 1);
}
}```