特定年份和月份的星期六和星期日的数量
答
我已经创建了一个使用计算方法来计算SATS和周日的功能。我还没有对它进行过测试。我已经在@ 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()
答
试试这个:
- 采取月份和年份。
- 在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()
CPU周期与可读性+复杂性+维护! – 2010-11-16 14:48:07
我同意,保持简单(愚蠢)通常是最好的方法。我认为@ p.campbell覆盖了迭代方法,所以发布了替代方案,如果函数在时间关键的应用程序中会非常有用 – DJIDave 2010-11-19 08:03:54