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.
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.
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:
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 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);