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

后端 未结 19 1034
野的像风
野的像风 2020-11-27 06:07

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

19条回答
  •  青春惊慌失措
    2020-11-27 06:35

    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.

提交回复
热议问题