2011-06-27 18 views

回答

3
Dim someDate As DateTime = ... 'input date 
Dim nextFriday As DateTime = someDate 
While nextFriday.DayOfWeek <> DayOfWeek.Friday 
    nextFriday = nextFriday.AddDays(1) 
End While 

Console.WriteLine(nextFriday) 
+0

不需要是循環 – dbasnett

8
Dim NextFriday as Date= GetNext(DayOfWeek.Friday) 

Function GetNext(ByVal d As DayOfWeek, Optional ByVal StartDate As Date = Nothing) As Date 
    If StartDate = DateTime.MinValue Then StartDate = Now 
    For p As Integer = 1 To 7 
     If StartDate.AddDays(p).DayOfWeek = d Then Return StartDate.AddDays(p) 
    Next 
End Function 

編輯:更新的答案,讓一個開始日期(可選)。

獲得下週五:

Dim NextFriday As Date = GetNext(DayOfWeek.Friday) 

什麼是下週五後15天從現在開始:

Dim AnotherFriday As Date = GetNext(DayOfWeek.Friday,now.addays(15)) 
+1

將它作爲日期對象的擴展來獲得更多樂趣。 – Stefan

+0

不需要循環 – dbasnett

+0

@dbasnett,聰明! – Stefan

7
' 
Public Function nextDOW(whDayOfWeek As DayOfWeek, _ 
         Optional theDate As DateTime = Nothing) As DateTime 
    'returns the next day of the week 
    If theDate = Nothing Then theDate = DateTime.Now 
    Dim d As DateTime = theDate.AddDays(whDayOfWeek - theDate.DayOfWeek) 
    Return If(d <= theDate, d.AddDays(7), d) 
End Function 
+0

我沒有投票-1,但我認爲d Stefan

+0

注意到並同意,已更正。循環回答起來投票,我的投票。得到愛是如此。 – dbasnett

+0

你有我的+1。 ;) 這是在行動中的「西方問題中最快的槍」。 (http://meta.stackexchange.com/questions/9731/fastest-gun-in-the-west-problem)。我想,隨着時間的推移,你會得到更多的選票,並且會得到更正。 – Stefan

0

又一個變化與以上那些,只是沒有循環:

Private Function GetFridayDate(StartingDate As Date, DayToGet As DayOfWeek, iDays As Integer) As Date 
     Return StartingDate.AddDays(iDays + (DayToGet - StartingDate.DayOfWeek)) 
End Function 

如何使用函數的示例n

Dim dtStartDate As Date 

dtStartDate = GetFridayDate(Now, DayOfWeek.Friday, -7) ' Last Week Friday 

dtStartDate = GetFridayDate(Now, DayOfWeek.Friday, 0) ' This Week Friday 

dtStartDate = GetFridayDate(Now, DayOfWeek.Friday, 7) ' Next Week Friday 

dtStartDate = GetFridayDate(Now, DayOfWeek.Friday, 14) ' Week after Next Friday 
相關問題