Given a date (of type DateTime
), how do I find the 3rd Friday in the month of that date?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
My reasoning goes like this
0
for Sunday5-(int)baseDay.DayOfWeek
to the 15thIn code:
Since there are only 7 possible results, you could also do this:
Sorry to jump in late on this... Might help someone else tho.
Begin rant: Loops, yuck. Too much code, yuck. Not Generic Enough, yuck.
Here's a simple function with a free overload.
Your usage:
Probably best to abstract this to a method to do any date/day combination:
(Extension Method)
Results:
Old post, but I found remarkably few decent answers online for this surely quite common problem! Mark Ransom's answer should be the last word on this algorithm-wise, but here is a C# helper class (in this case I think clearer than extensions) for anyone who wants a quick answer to the common problems of "first day of week in month", "xth day of week in month" and "last day of week in month".
I modified it to return
DateTime.MinValue
if the Xth day of the week falls outside the provided month rather than wrapping to the next month, because that to me seems more useful.I've thrown in a LINQPad-runnable example program too.
Prints: