2

我在 VB.net 中寻找一个函数,它返回一个月中给定一周的指定工作日的日期。类似于 Outlook 约会的东西。

例如:每月的第一个星期一、每月的第二个星期四或每月的最后一个星期六

我进行了搜索,但找不到任何足以满足所有选项的通用性。所以我创建了自己的并想分享它。

4

2 回答 2

3

这是我想出的:

Public Function GetDate()

    Dim dt As Date = Today

    Dim FirstWeek As Integer = 1
    Dim SecondWeek As Integer = 2
    Dim ThirdWeek As Integer = 3
    Dim FourthWeek As Integer = 4
    Dim LastWeek As Integer = 5

    MsgBox(GetNthDayOfNthWeek(dt, DayOfWeek.Monday, LastWeek).ToString)

End Function

Public Function GetNthDayOfNthWeek(ByVal dt As Date, ByVal DayofWeek As Integer, ByVal WhichWeek As Integer) As Date
    'specify which day of which week of a month and this function will get the date
    'this function uses the month and year of the date provided

    'get first day of the given date
    Dim dtFirst As Date = DateSerial(dt.Year, dt.Month, 1)

    'get first DayOfWeek of the month
    Dim dtRet As Date = dtFirst.AddDays(6 - dtFirst.AddDays(-(DayofWeek + 1)).DayOfWeek)

    'get which week
    dtRet = dtRet.AddDays((WhichWeek - 1) * 7)

    'if day is past end of month then adjust backwards a week
    If dtRet >= dtFirst.AddMonths(1) Then
        dtRet = dtRet.AddDays(-7)
    End If

    'return
    Return dtRet

End Function

享受!

于 2013-07-09T05:41:20.457 回答
1
Public Function GetLastDayOfMonth(ByVal iMonth As Integer, ByVal iYear As Integer) As Integer
    Dim LastDate = DateSerial(iYear, iMonth + 1, 0)
    GetLastDayOfMonth = LastDate.Day

    Return GetLastDayOfMonth
End Function

Private Function GetWeekNumberOfMonth(ByVal Dt As Date) As Integer
        Dim LastDate = New DateTime(Dt.Year, Dt.Month, GetLastDayOfMonth(Dt.Month, Dt.Year), Dt.Hour, Dt.Minute, Dt.Second, Dt.Kind)
        Dim weekNumber As Integer = Math.Ceiling(Dt.Day / 7)
        If weekNumber = 4 Then
            Dim dateDiff = CInt((LastDate - Dt).TotalDays)
            If dateDiff < 7 Then weekNumber = 5
        End If

        Return weekNumber
    End Function
于 2015-07-31T19:24:44.480 回答