Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if this Monday is last Monday in a month

Tags:

c#

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 fine. But it not checks a last day ( for me it's when n = 5). How to modify it?
Thanks.

like image 267
user1230307 Avatar asked Feb 25 '12 06:02

user1230307


People also ask

How do you find the last Monday of a month in Excel?

WEEKDAY(EOMONTH(A2,0) – 2) – This formula returns the day of the week corresponding to the date that is 2 days before the last day of the month. The formula basically helps us find how many days we need to roll back from the last day of the month in order to get to the last Monday of the month.

How can I get last Monday of the month in PHP?

function lastDayOfMonth($month, $year) { switch ($month) { case 2: # if year is divisible by 4 and not divisible by 100 if (($year % 4 == 0) && ($year % 100) > 0) return 29; # or if year is divisible by 400 if ($year % 400 == 0) return 29; return 28; case 4: case 6: case 9: case 11: return 30; default: return 31; } } ...

How do I get last Monday date in Excel?

It does this my using EOMONTH to get the last day of the month, then adding one day: = EOMONTH ( B5 , 0 ) + 1 Next, the formula calculates the number of days... The DAY function returns the day value for a date.


1 Answers

The method below checks the given date is the last date of week of month.

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

So there is 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;
}
like image 189
arunes Avatar answered Sep 28 '22 03:09

arunes