Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wrote a type extender to allow me to add (or subtract) weekdays to a given date. Maybe this will help you. Works great, so please vote for my post if this helped you.</p> <pre><code> /// &lt;summary&gt; /// Adds weekdays to date /// &lt;/summary&gt; /// &lt;param name="value"&gt;DateTime to add to&lt;/param&gt; /// &lt;param name="weekdays"&gt;Number of weekdays to add&lt;/param&gt; /// &lt;returns&gt;DateTime&lt;/returns&gt; public static DateTime AddWeekdays(this DateTime value, int weekdays) { int direction = Math.Sign(weekdays); int initialDayOfWeek = Convert.ToInt32(value.DayOfWeek); //--------------------------------------------------------------------------- // if the day is a weekend, shift to the next weekday before calculating if ((value.DayOfWeek == DayOfWeek.Sunday &amp;&amp; direction &lt; 0) || (value.DayOfWeek == DayOfWeek.Saturday &amp;&amp; direction &gt; 0)) { value = value.AddDays(direction * 2); weekdays += (direction * -1); // adjust days to add by one } else if ((value.DayOfWeek == DayOfWeek.Sunday &amp;&amp; direction &gt; 0) || (value.DayOfWeek == DayOfWeek.Saturday &amp;&amp; direction &lt; 0)) { value = value.AddDays(direction); weekdays += (direction * -1); // adjust days to add by one } //--------------------------------------------------------------------------- int weeksBase = Math.Abs(weekdays / 5); int addDays = Math.Abs(weekdays % 5); int totalDays = (weeksBase * 7) + addDays; DateTime result = value.AddDays(totalDays * direction); //--------------------------------------------------------------------------- // if the result is a weekend, shift to the next weekday if ((result.DayOfWeek == DayOfWeek.Sunday &amp;&amp; direction &gt; 0) || (result.DayOfWeek == DayOfWeek.Saturday &amp;&amp; direction &lt; 0)) { result = result.AddDays(direction); } else if ((result.DayOfWeek == DayOfWeek.Sunday &amp;&amp; direction &lt; 0) || (result.DayOfWeek == DayOfWeek.Saturday &amp;&amp; direction &gt; 0)) { result = result.AddDays(direction * 2); } //--------------------------------------------------------------------------- return result; } </code></pre>
 

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