Check if this monday is the last monday of the month

I use this code from another question:

private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){ int d = date.Day; return date.DayOfWeek == dow && (d-1)/7 == (n-1); } 

It works great. But he does not check the last day (for me it is with n = 5). How to change it?
Thanks.

+4
source share
2 answers

In the method below, the specified date is the last date of the week of the month.

 private bool IsLastOfMonth(DateTime date) { var oneWeekAfter = date.AddDays(7); return oneWeekAfter.Month != date.Month; } 

So there is a new method, it just checks Mondays

 private bool IsLastMonday(DateTime date) { if (date.DayOfWeek != DayOfWeek.Monday) return false; // it is not monday // the next monday is... var oneWeekAfter = date.AddDays(7); // and is it in same month?, if it is, that means its not last monday return oneWeekAfter.Month != date.Month; } 
+9
source

Let's take March 30th,

 d = 30, (date.DayOfWeek == DayOfWeek.Friday) == true, (30-1)=29, 29/7 = 4 4 == (5-1) 

So it works

To check if DayOfWeek is really the last time in mothth, you can use

 return date.AddDays(7).Month != date.Month; 
+2
source

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


All Articles