Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of months between two dates

Tags:

c#

datetime

range

I have the following snippet that I use to get the individual dates between two dates:

DateTime[] output = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
    .Select(offset => startDate.AddDays(offset))
    .ToArray(); 

However, the following section

endDate.Subtract(startDate).Days

does not have a .Months to return the months in the date range.

For example, if I provide 1/1/2010 and 6/1/2010 I would expect to return 1/1/2010, 2/1/2010, 3/1/2010, 4/1/2010, 5/1/2010 and 6/1/2010.

Any ideas?

like image 555
Andy Evans Avatar asked Oct 08 '10 14:10

Andy Evans


People also ask

How to get number of months between two dates js?

To get the number of months between 2 dates: Use the getMonth() method to calculate the month difference between the two dates. Use the getFullYear() method to calculate the difference in years between the dates. Multiply the year difference by 12 and return the sum.


1 Answers

Try this:

static IEnumerable<DateTime> monthsBetween(DateTime d0, DateTime d1)
{
    return Enumerable.Range(0, (d1.Year - d0.Year) * 12 + (d1.Month - d0.Month + 1))
                     .Select(m => new DateTime(d0.Year, d0.Month, 1).AddMonths(m));
}

This includes both the starting month and the ending month. This finds how many months there is, and then creates a new DateTime based on d0´s year and month. That means the months are like yyyy-MM-01. If you want it to includes the time and day of d0 you can replace new DateTime(d0.Year, d0.Month, 1).AddMonths(m) by d0.AddMonths(m).

I see you need an array, in that case you just use monthsBetween(..., ...).ToArray() or put .ToArray() inside the method.

like image 89
Lasse Espeholt Avatar answered Oct 12 '22 23:10

Lasse Espeholt