5

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.

2

2 Answers 2

12

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;
}
1
  • i added a new method for just checks monday.
    – arunes
    Feb 25, 2012 at 9:42
2

Lets take March 30,

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

So it works

To only check if DayOfWeek is last in mothth you can use

return date.AddDays(7).Month != date.Month;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.