检查日期是否在VB.NET的第三周

时间:2013-05-30 09:21:42

标签: vb.net date

想知道VB.net中是否有一个函数可以告诉我它属于哪个星期。

即。         2013-05-10 =“第二周的一部分”         2013-05-31 =“5h周的一部分”

datetimepicker是否附带了这个函数? 在此先感谢!

1 个答案:

答案 0 :(得分:2)

您可以将所选月份第一天的WeekOfYear与所选日期的WeekOfYear进行比较。

Dim dtDate1 As DateTime = New DateTime(2013, 5, 10)
MsgBox(DatePart(DateInterval.WeekOfYear, dtDate1, FirstDayOfWeek.System) - DatePart(DateInterval.WeekOfYear, New DateTime(dtDate1.Year, dtDate1.Month, 1), FirstDayOfWeek.System) + 1)

Dim dtDate2 As DateTime = New DateTime(2013, 5, 31)
MsgBox(DatePart(DateInterval.WeekOfYear, dtDate2, FirstDayOfWeek.System) - DatePart(DateInterval.WeekOfYear, New DateTime(dtDate2.Year, dtDate2.Month, 1), FirstDayOfWeek.System) + 1)

或作为一项功能:

Function GetWeekInMonth(dtDate As Date) As Integer
    Dim DateWeekNumber As Integer = DatePart(DateInterval.WeekOfYear, dtDate, FirstDayOfWeek.System)
    Dim MonthStartWeek As Integer = DatePart(DateInterval.WeekOfYear, New DateTime(dtDate.Year, dtDate.Month, 1), FirstDayOfWeek.System)
    Return DateWeekNumber - MonthStartWeek + 1
End Function  

但是添加为date-object的扩展名非常棒:

Module Extensions
    <System.Runtime.CompilerServices.Extension> _
    Public Function GetWeekInMonth(dtDate As Date) As Integer
        Dim DateWeekNumber As Integer = DatePart(DateInterval.WeekOfYear, dtDate, FirstDayOfWeek.System)
        Dim MonthStartWeek As Integer = DatePart(DateInterval.WeekOfYear, New DateTime(dtDate.Year, dtDate.Month, 1), FirstDayOfWeek.System)
        Return DateWeekNumber - MonthStartWeek + 1
    End Function

End Module

现在,您可以在项目中的每个日期对象上使用.GetWeekInMonth。

Dim weeknr As Integer = CDate("2013-05-31").GetWeekInMonth