Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'll take a stab at this... You can use Linq to generate all the date ranges at once. It's not exactly the prettiest query, but it works.</p> <pre><code>DateTime start = ... DateTime end = ... var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar; var range = from y in Enumerable.Range(start.Year, end.Year - start.Year + 1) let maxMonth = y &lt; end.Year ? cal.GetMonthsInYear(y) : end.Month let minMonth = y &gt; start.Year ? 1 : start.Month from m in Enumerable.Range(minMonth, maxMonth - minMonth + 1) let isStart = (y == start.Year &amp;&amp; m == start.Month) let isEnd = (y == end.Year &amp;&amp; m == end.Month) select new { StartDate = isStart ? start : new DateTime(y, m, 1), EndDate = isEnd ? end : new DateTime(y, m, cal.GetDaysInMonth(y, m)), NumberOfMonths = isStart || isEnd ? .5 : 1 }; </code></pre> <p>It iterates over the years from <code>start</code> to <code>end</code>, then iterates over the months in each year, with special handling on the edge cases (<code>isStart</code> and <code>isEnd</code>). This basic algorithm can be encapsulated in a function like this:</p> <pre><code>public class DateTimeRange { Date StartDate { get; set; } Date EndDate { get; set; } float NumberOfMonths { get; set; } } public static IEnumerable&lt;DateTimeRange&gt; SplitByMonths(DateTime start, DateTime end, Calendar cal) { return ( from y in Enumerable.Range(start.Year, end.Year - start.Year + 1) let maxMonth = y &lt; end.Year ? cal.GetMonthsInYear(y) : end.Month let minMonth = y &gt; start.Year ? 1 : start.Month from m in Enumerable.Range(minMonth, maxMonth - minMonth + 1) let isStart = (y == start.Year &amp;&amp; m == start.Month) let isEnd = (y == end.Year &amp;&amp; m == end.Month) select new DateTimeRange { StartDate = isStart ? start : new DateTime(y, m, 1), EndDate = isEnd ? end : new DateTime(y, m, cal.GetDaysInMonth(y, m)), NumberOfMonths = isStart || isEnd ? .5 : 1 }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload