Question Future Date Calculation

fripper

New member
Joined
Jan 29, 2011
Messages
1
Programming Experience
5-10
After unsuccessfully searching the docs for an hour or so I resort to this forum ... how do I calculate, say, the date of next Wednesday (in VB .Net)? I KNOW there's a way to do that but my mind is a blank

Thanks.
 
TimeSpan has nothing to do with dates. Use the Date data type and its DayOfWeek property, either calculate the difference or AddDay until you reach the target DayOfWeek value. Here are examples of both:
VB.NET:
Public Function GetNextWeekDay(ByVal day As Date, ByVal target As DayOfWeek) As Date
    Do Until day.DayOfWeek = target
        day = day.AddDays(1)
    Loop
    Return day
End Function
VB.NET:
Public Function GetNextWeekDay(ByVal day As Date, ByVal target As DayOfWeek) As Date
    Dim dayweekday = CInt(day.DayOfWeek)
    Dim add = target - dayweekday
    If add <= 0 Then add += 7
    Return day.AddDays(add).Date
End Function
VB.NET:
Dim nextWednesday = GetNextWeekDay(Date.Now, DayOfWeek.Wednesday)
 
hey johnH, the date.AddDays(), just never seem to work the right way for me, even posted about it on this forum, i just ended up using the TimeSpan.
 
hey johnH, the date.AddDays(), just never seem to work the right way for me, even posted about it on this forum, i just ended up using the TimeSpan.

It works exactly as advertised: it adds the specified number of days to the specified date. If it didn't do what you wanted then you used it incorrectly. As you've never actually shown us what you did, we can't tell you what you did wrong. JohnH is quite correct that there's no place for a TimeSpan in this calculation.
 
Back
Top