我使用以下代码确定下一周每一天的日期:
Dim someDate As DateTime = Date.Today
Dim nextMonday As DateTime = someDate
While nextMonday.DayOfWeek <> DayOfWeek.Monday
nextMonday = nextMonday.AddDays(1)
End While
Dim nextTuesday As DateTime = someDate
While nextTuesday.DayOfWeek <> DayOfWeek.Tuesday
nextTuesday = nextTuesday.AddDays(1)
End While
除了与当天相同的未来日外,它的效果很好。例如。今天是2016年8月8日星期五,代码也返回2016年8月1日,它实际上应该返回15/1/2016。其他日子的所有日期都是正确的。 有什么想法吗?
此致
答案 0 :(得分:1)
您可以使用以下扩展方法:
<System.Runtime.CompilerServices.Extension()> _
Public Function StartOfWeek(dt As DateTime, firstDayOfWeek As DayOfWeek) As DateTime
Dim diff As Int32 = dt.DayOfWeek - firstDayOfWeek
If diff < 0 Then
diff += 7
End If
Return dt.AddDays(-1 * diff).Date
End Function
如果您希望下周完成List(Of Date)
:
Dim startOfNextWeek As Date = Date.Today.AddDays(7).StartOfWeek(DayOfWeek.Monday)
Dim nextWeek = Enumerable.Range(0, 7).Select(Function(d) startOfNextWeek.AddDays(d)).ToList()
没有LINQ:
Dim nextWeek As New List(Of Date)
For d As Int32 = 0 To 6
nextWeek.Add(startOfNextWeek.AddDays(d))
Next
答案 1 :(得分:0)
使用循环遍历值的函数会更好。这样的事情应该做你想做的事情:
Public Function FindNextDayOfWeek(startDate As Date, dayToFind As DayOfWeek) As Date
Dim adjustment = 6 + (dayToFind - startDate.DayOfWeek)
If adjustment > 7 Then adjustment -= 7
Return startDate.AddDays(adjustment)
End Function
试验:
FindNextDayOfWeek(#2015-01-13#, DayOfWeek.Tuesday) 'returns 19/01/2015
FindNextDayOfWeek(#2015-01-11#, DayOfWeek.Wednesday) ' returns 13/01/2015
FindNextDayOfWeek(#2015-01-11#, DayOfWeek.Monday) 'returns 18/01/2015
答案 2 :(得分:0)
此方法适用于您:
Private Function GetNextDayOfWeek(afterDate As Date, targetDayOfWeek As DayOfWeek) As DateTime
Const TotalDaysInWeek = DayOfWeek.Saturday - DayOfWeek.Sunday + 1 '+1 to account for zero indexed.
Dim daysToAdd As Integer
Select Case targetDayOfWeek
Case Is < afterDate.DayOfWeek
daysToAdd = afterDate.DayOfWeek - targetDayOfWeek - 1
Case Is = afterDate.DayOfWeek
daysToAdd = TotalDaysInWeek 'need to find exactly one week from "afterDate"
Case Is > afterDate.DayOfWeek
daysToAdd = targetDayOfWeek - afterDate.DayOfWeek
End Select
Return afterDate.AddDays(daysToAdd)
End Function