Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the 3rd Friday in a month with C#?

Tags:

c#

.net

datetime

Given a date (of type DateTime), how do I find the 3rd Friday in the month of that date?

like image 299
Paul Fryer Avatar asked Mar 24 '11 15:03

Paul Fryer


1 Answers

I'm going to repeat my answer from here with one little addition.

The language-agnostic version:

To get the first particular day of the month, start with the first day of the month: yyyy-mm-01. Use whatever function is available to give a number corresponding to the day of the week; in C# this would be DateTime.DayOfWeek. Subtract that number from the day you are looking for; for example, if the first day of the month is Wednesday (3) and you're looking for Friday (5), subtract 3 from 5, leaving 2. If the answer is negative, add 7. Finally add that to the first of the month; for my example, the first Friday would be the 3rd.

To get the last Friday of the month, find the first Friday of the next month and subtract 7 days.

To get the 3rd Friday of the month, add 14 days to the first Friday.

like image 124
Mark Ransom Avatar answered Sep 29 '22 11:09

Mark Ransom