我正在尝试使用扩展方法将一周添加到给定日期 然后检索一周中第一天的日期(从AddWeeks函数返回的日期)
Private Sub doSomething()
Dim dt As DateTime = DateTime.Now.AddWeeks(1)
dt = dt.StartOfWeek(dt.DayOfWeek) ' The year returned here is 0001
End Sub
<Extension()>
Public Function AddWeeks(ByVal dt As DateTime, numOfWeeks As Integer) As
DateTime
Return dt.AddDays(numOfWeeks * 7)
End Function
<Extension()>
<Extension()>
Public Function StartOfWeek(ByVal dt As DateTime, start As DayOfWeek) As DateTime
Dim diff As Integer = dt.DayOfWeek - start
If (diff < 0) Then
diff += 7
End If
Return dt.AddDays(-diff)
End Function
此代码的问题在于返回的日期是错误的年份,它总是像dd/mm/0001
答案 0 :(得分:0)
要到达一周的第一天,请尝试扣除一天,直到您到达星期一为止:
Public Function StartOfWeek(ByVal dt As DateTime, start As DayOfWeek) As DateTime
If Not dt.DayOfWeek = DayOfWeek.Monday Then
While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(-1)
End While
End If
Return dt
End Fuction