C #: Find out which Monday is the third Monday of the month?

If I write some code in C # that goes through a year of dates (iteration by day) and wants something special to happen every third Monday of the month, how can I do this?

In other words, what is the best way to find which Monday of the month is the current current Monday?

+4
source share
4 answers
public bool IsThirdMondayOfMonth(DateTime dt) { if(dt.DayOfWeek == DayOfWeek.Monday && dt.Day > 14 && dt.Day <= 21) { return true; } return false; } 
+10
source

I do not think that your β€œin other words” really repeats the problem that you describe in the first place, so I will answer both.

Here's a pretty simple method that will determine the nth occurrence on a specific day of the week for a given month in a given year.

 public static DateTime DayOccurrence(int year, int month, DayOfWeek day, int occurrenceNumber) { DateTime start = new DateTime(year, month, 1); DateTime first = start.AddDays((7 - ((int)start.DayOfWeek - (int)day)) % 7); return first.AddDays(7 * (occurrenceNumber - 1)); } 

Determining which Monday (or any other day) of the month for which it is given is much simpler; just take the ceiling of the day of the month / 7:

 public static int DayOccurrence(DateTime date) { return (int)Math.Ceiling(date.Day / 7.0); } 
+8
source

Find Monday, which is between 15 and 21 inclusive.

+1
source

I don't know if there is a date processing library to do what you want, but you can easily write your own functions:

 using System; class Program { static void Main(string[] args) { int year = 2010; int month = 05; DateTime thirdMonday = ThirdMonday(year, month); } private static DateTime ThirdMonday(int year, int month) { for (int day = 1; day <= DateTime.DaysInMonth(year, month); ++day) { DateTime dt = new DateTime(year, month, day); if (dt.DayOfWeek == DayOfWeek.Monday) { return dt.AddDays(14); } } // this should never happen throw new Exception(); } } 
0
source

Source: https://habr.com/ru/post/1309677/


All Articles