How do I get the total number of a particular day in a particular month/year?
Let's say i want to know the number of Mondays in Febr开发者_如何学Pythonuary 2014.
I understand this will use the DateTime class, but would like to see some coding examples please.
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);
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
Why iterate through the complete month while you can calculate it?
Public Function CountDayOfWeekInMonth(ByVal DateTargeted As Date, Optional ByVal StartingDay As DayOfWeek = DayOfWeek.Sunday) As Integer
Dim dCountingDate As New DateTime(DateTargeted.Year, DateTargeted.Month, 1)
Dim iDaysInMonth As Integer = DateTime.DaysInMonth(dCountingDate.Year, dCountingDate.Month)
Dim iDaysToAdd As Integer = (7 + CType(StartingDay, Integer) - dCountingDate.DayOfWeek) Mod 7
Dim iFirstStartingDay As Integer = dCountingDate.AddDays(iDaysToAdd).Day
Return Math.Truncate((iDaysInMonth - iFirstStartingDay) / 7) + 1
End Function
Used as follow
Dim iResult as Integer = CountDayOfWeekInMonth(New DateTime(2012, 04, 30), DayOfWeek.Monday)
精彩评论