Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Probably best to abstract this to a method to do any date/day combination:</p> <p>(Extension Method)</p> <pre><code>public static bool TryGetDayOfMonth(this DateTime instance, DayOfWeek dayOfWeek, int occurance, out DateTime dateOfMonth) { if (instance == null) { throw new ArgumentNullException("instance"); } if (occurance &lt;= 0 || occurance &gt; 5) { throw new ArgumentOutOfRangeException("occurance", "Occurance must be greater than zero and less than 6."); } bool result; dateOfMonth = new DateTime(); // Change to first day of the month DateTime dayOfMonth = instance.AddDays(1 - instance.Day); // Find first dayOfWeek of this month; if (dayOfMonth.DayOfWeek &gt; dayOfWeek) { dayOfMonth = dayOfMonth.AddDays(7 - (int)dayOfMonth.DayOfWeek + (int)dayOfWeek); } else { dayOfMonth = dayOfMonth.AddDays((int)dayOfWeek - (int)dayOfMonth.DayOfWeek); } // add 7 days per occurance dayOfMonth = dayOfMonth.AddDays(7 * (occurance - 1)); // make sure this occurance is within the original month result = dayOfMonth.Month == instance.Month; if (result) { dateOfMonth = dayOfMonth; } return result; } </code></pre> <p>Results:</p> <pre><code>DateTime myDate = new DateTime(2013, 1, 1) DateTime dateOfMonth; myDate.TryGetDayOfMonth(DayOfWeek.Sunday, 1, out dateOfMonth) // returns: true; dateOfMonth = Sunday, 1/6/2013 myDate.TryGetDayOfMonth(DayOfWeek.Sunday, 4, out dateOfMonth) // returns: true; dateOfMonth = Sunday, 1/27/2013 myDate.TryGetDayOfMonth(DayOfWeek.Sunday, 5, out dateOfMonth) // returns: false; myDate.TryGetDayOfMonth(DayOfWeek.Wednesday, 1, out dateOfMonth) // returns: true; dateOfMonth = Wednesday, 1/2/2013 myDate.TryGetDayOfMonth(DayOfWeek.Wednesday, 4, out dateOfMonth) // returns: true; dateOfMonth = Wednesday, 1/23/2013 myDate.TryGetDayOfMonth(DayOfWeek.Wednesday, 5, out dateOfMonth) // returns: true; dateOfMonth = Wednesday, 1/30/2013 // etc </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.
 

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