开发者

number of Saturdays and Sundays of a specific year and month

开发者 https://www.devze.com 2023-01-25 10:47 出处:网络
Using Visual开发者_运维问答 Basic .NET, how can you find the number of Saturdays and Sundays of a specific year and month?I have created a function that uses a calculation method to calculate the Satu

Using Visual开发者_运维问答 Basic .NET, how can you find the number of Saturdays and Sundays of a specific year and month?


I have created a function that uses a calculation method to calculate the Saturdays and Sundays. I have not tested it to death. I have tested the performance of both and the calculation method (below) and the iteration method in @p.campbell's answer, the result in milliseconds for 10,000 calls were.

Calculation: 7
Iteration: 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()


Try this:

  • take a month and year.
  • get the first of the month for that month/year in a DateTime
  • find the 'end' of the month, or rather, the beginning of the next month.
  • loop and count the num of your 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()
0

精彩评论

暂无评论...
验证码 换一张
取 消