2013-05-30 88 views
0

想知道是否有一個VB.net函數內置,可以告訴我它屬於哪一週。檢查日期是否在本月的第三週VB.NET

即。 2013年5月10日= 5H周‘

的部分做的的DateTimePicker配備此功能? 在此先感謝「第二週」 2013年5月31日=的一部分’!

回答

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 

但是,這將是真正偉大添加爲一個擴展日期對象:

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 
+2

在答案中增加了一些示例。我喜歡擴展! ;) – Stefan

+0

非常感謝! –

相關問題