定义扩展方法
Imports System.Runtime.CompilerServices
Module DateExtensions
<Extension()>
Public Function GetMonday(ByVal dt As DateTime) as DateTime
While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(-1)
End While
return dt
End Function
End Module
并称它为
prday = prday.GetMonday()
或者我们可以让它通用
Public Function GetPreviousDayOfWeek(ByVal dt As DateTime, prevDay As DayOfWeek) as DateTime
While dt.DayOfWeek <> prevDay
dt = dt.AddDays(-1)
End While
return dt
End Function
正如@dbasnett 所指出的,数学比循环快,我们可以处理星期天是一周的第一天的情况。所以更好的方法应该是
Public Function GetMonday(ByVal dt As DateTime) as DateTime
Dim diff = Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek - DayOfWeek.Monday
dt = dt.AddDays(diff)
return dt.AddDays(DayOfWeek.Monday - dt.DayOfWeek)
End Function