如何获取特定月份/年中特定日期的总数?

时间:2010-09-03 19:08:26

标签: c# datetime

假设我想知道2014年2月的星期一数量。

我知道这将使用DateTime类,但是希望看到一些编码示例。

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:3)

@Anthony给出了一个很好的Linq解决方案,这是一个更传统的实现。

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;
}

使用如下

int numberOfThursdays = CountDayOfWeekInMonth(2014, 2, DayOfWeek.Thursday);  

答案 2 :(得分:2)

这个应该帮助你作为一个开始:

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

您只需将其调整为使用月份/年而不是仅使用年份。

几乎可以得到你想要的解决方案:

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

答案 3 :(得分:0)

为什么要在计算完整月份的情况下进行迭代?

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

使用如下

Dim iResult as Integer = CountDayOfWeekInMonth(New DateTime(2012, 04, 30), DayOfWeek.Monday)