Create an array of months between two dates

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

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

However the next section

 endDate.Subtract(startDate).Days 

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

For example, if I give 1/1/2010 and 6/1/2010, I expect to be back on January 1, 2010, 2/1/2010, 3/1/2010, 4/1/2010, 5/1/2010 and 6/1/2010.

Any ideas?

+7
c # datetime range
source share
4 answers

Try the following:

 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 start month and the end month. This finds how many months are, and then creates a new DateTime based on d0 year and month. This means that months are like yyyy-MM-01 . If you want it to include the time and day d0 , you can replace new DateTime(d0.Year, d0.Month, 1).AddMonths(m) with d0.AddMonths(m) .

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

+25
source share

Since I just need a year and a month between the two dates, I cheated on Lasse Espeholt a bit. suppose: d0 = 2012-11-03

d1 = 2013-02-05

The result will be something like this:

2012-11

2012-12

2013-01

2013-02

  private List<Tuple<int,int>> year_month_Between(DateTime d0, DateTime d1) { List<DateTime> datemonth= Enumerable.Range(0, (d1.Year - d0.Year) * 12 + (d1.Month - d0.Month + 1)) .Select(m => new DateTime(d0.Year, d0.Month, 1).AddMonths(m)).ToList(); List<Tuple<int, int>> yearmonth= new List<Tuple<int,int>>(); foreach (DateTime x in datemonth) { yearmonth.Add(new Tuple<int, int>(x.Year, x.Month)); } return yearmonth; } 
+3
source share

You can list several months with:

 private static IEnumerable<DateTime> ByMonths(DateTime startDate, DateTime endDate) { DateTime cur = startDate; for(int i = 0; cur <= endDate; cur = startDate.AddMonths(++i)) { yield return cur; } } 

and then call ToArray() if you want an array. He is good enough that values ​​that are likely to be what is required; for example, if you start on January 31st you will get February 28th th (or 29th th in leap years), then March 31st> st then April 30th th , etc.

+1
source share

Is this what you are looking for? The requirement is very mixed.

 DateTime[] calendarMonthBoundaries = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days) .Select(offset => startDate.AddDays(offset)) .Where(date => date.Day == 1) .ToArray(); 
0
source share

All Articles