tags:

views:

128

answers:

3

Let's say i want to know the number of Mondays in February 2014.

I understand this will use the DateTime class, but would like to see some coding examples please.

+2  A: 

This one should help you as a start:

How To: Get all Mondays in a given year in C#

You just have to adapt it to use month/year instead of only year.

Solution that almost get what you want:

List the First Monday of every month using C# and VB.NET

Leniel Macaferi
+8  A: 
static int NumberOfParticularDaysInMonth(int year, int month, DayOfWeek dayOfWeek)
{
    DateTime startDate = new DateTime(year, month, 1);
    int totalDays = startDate.AddMonths(1).Subtract(startDate).Days;

    int answer = Enumerable.Range(1, totalDays)
        .Select(item => new DateTime(year, month, item))
        .Where(date => date.DayOfWeek == dayOfWeek)
        .Count();

    return answer;
}

...

int numberOfThursdays = NumberOfParticularDaysInMonth(2010, 9, DayOfWeek.Thursday);
Anthony Pegram
+3  A: 

@Anthony has given a nice Linq solution, here is a more traditional implementation.

static int CountDayOfWeekInMonth(int year, int month, DayOfWeek dayOfWeek)
{
  DateTime startDate = new DateTime(year, month, 1);
  int days = DateTime.DaysInMonth(startDate.Year, startDate.Month);
  int weekDayCount = 0;
  for (int day = 0; day < days; ++day)
  {
    weekDayCount += startDate.AddDays(day).DayOfWeek == dayOfWeek ? 1 : 0;        
  }
  return weekDayCount;
}

Used as follows

int numberOfThursdays = CountDayOfWeekInMonth(2014, 2, DayOfWeek.Thursday);  
Chris Taylor
+1 . That being said, I think `if (startDate.AddDays(day).DayOfWeek == dayOfWeek) weekDayCount++;` is more readable. I don't like to use the `?` operator just to avoid an if statement, though avoiding an if-else or avoiding the need to create a temporary variable bothers me less. Maybe I'm biased because I don't mind one-line if statements.
Brian
Good answer. You know you could cheat to boost this along. For example, once you've found the first dayOfWeek match, there's no need to simply "++" the day. You can += 6 within the loop, then the next ++ will already be the next dayOfWeek match. (Another reason to use the `if` statement favored by @Brian.)
Anthony Pegram
@Anthony: Let's not worry about optimizations until there is a performance bottleneck. Your proposal makes the code slightly more complicated for a benefit that has an incredibly low chance of actually mattering.
Brian