I have a StartDate & EndDate variables
DateTime startDate = new Date(2021,02,15);
DateTime endDate = new Date(2021,08,18);
How to generate a list of periods (In Months) like the following
class Period
{
DateTime FromDate;
DateTime ToDate;
}
List<Period> periodsList = new List<Period>();
content the following
{FromDate: '2021-02-15', ToDate: '2021-02-28'}
{FromDate: '2021-03-01', ToDate: '2021-03-31'}
{FromDate: '2021-04-01', ToDate: '2021-04-30'}
{FromDate: '2021-05-01', ToDate: '2021-05-31'}
{FromDate: '2021-06-01', ToDate: '2021-06-30'}
{FromDate: '2021-07-01', ToDate: '2021-07-31'}
{FromDate: '2021-08-01', ToDate: '2021-08-18'}
CodePudding user response:
Approach with simple for-loop
DateTime startDate = new DateTime(2021, 02, 15);
DateTime endDate = new DateTime(2021, 08, 18);
List<Period> periodsList = new List<Period>();
for (DateTime i = startDate; i < endDate; i = i.AddMonths(1))
{
periodsList.Add(new Period()
{
FromDate = new[] { new DateTime(i.Year, i.Month, 1), startDate }.Max(),
ToDate = new[] { new DateTime(i.Year, i.Month, 1).AddMonths(1).AddDays(-1), endDate }.Min()
});
}