特定年份和月份的星期六和星期日数

时间:2010-11-16 01:41:59

标签: .net vb.net algorithm

使用Visual Basic .NET,如何找到特定年份和月份的星期六和星期日数?

2 个答案:

答案 0 :(得分:1)

试试这个:

  • 需要一个月和一年。
  • 在DateTime
  • 中获得该月/年的第一个月
  • 找到月份的“结束”,或者更确切地说,是下个月的开始。
  • 循环并计算DayOfWeek的数量。
Dim month As Integer = 8
Dim year As Integer = 2010

Dim current As New DateTime(year, month, 1)
Dim ending As DateTime = start.AddMonths(1)

Dim numSat As Integer = 0
Dim numSun As Integer = 0

While current < ending
    If current.DayOfWeek = DayOfWeek.Saturday Then
        numSat += 1
    End If
    If current.DayOfWeek = DayOfWeek.Sunday Then
        numSun += 1
    End If
    current = current.AddDays(1)
End While


Console.WriteLine("Sats: " & numSat)
Console.WriteLine("Suns: " & numSun)
Console.ReadLine()

答案 1 :(得分:1)

我创建了一个使用计算方法来计算Sats和Sundays的函数。我还没有测试过它。我在@ p.campbell的答案中测试了两者的性能和计算方法(下面)和迭代方法,10,000次调用的结果以毫秒为单位。

计算:7 迭代:39

希望有所帮助。

戴夫

    Dim month As Integer = 12
    Dim year As Integer = 2011

    'Calculate the Start and end of the month
    Dim current As New DateTime(year, month, 1)
    Dim ending As DateTime = current.AddMonths(1)

    'Ints to hold the results
    Dim numSat As Integer = 0
    Dim numSun As Integer = 0

    'Numbers used in the calculation
    Dim dateDiff As Integer = (ending.Date - current.Date).Days
    Dim firstDay As DayOfWeek = current.DayOfWeek

    'Figure out how many whole weeks are in the month, there must be a Sat and Sunday in each
    ' NOTE this is integer devision
    numSat = dateDiff / 7
    numSun = dateDiff / 7

    'Calculate using the day of the week the 1st is and how many days over full weeks there are
    ' NOTE the Sunday requires a bit extra as Sunday is value 0 and Saturday is value 6
    numSat += If((firstDay + (dateDiff Mod 7)) > (DayOfWeek.Saturday), 1, 0)
    numSun += If(((firstDay + (dateDiff Mod 7)) > (DayOfWeek.Saturday + 1)) Or (firstDay = DayOfWeek.Sunday And (dateDiff Mod 7 = 1)), 1, 0)

    'Output the results
    Console.WriteLine("Sats: " & numSat)
    Console.WriteLine("Suns: " & numSun)
    Console.ReadLine()