Given a Date, how can I get the date of following Friday (or any other weekday) in VB.NET in .NET Framework 2.0?
Use the DateTime. DayOfWeek or DateTimeOffset. DayOfWeek property to retrieve a DayOfWeek value that indicates the day of the week. If necessary, cast (in C#) or convert (in Visual Basic) the DayOfWeek value to an integer.
You must enclose a Date literal within number signs ( # # ). You must specify the date value in the format M/d/yyyy, for example #5/31/1993# , or yyyy-MM-dd, for example #1993-5-31# . You can use slashes when specifying the year first.
int NumWeeks = 30; DateTime StartDate, EndDate; DateTime BaseDate = new DateTime(2010, 1, 1); BaseDate = BaseDate. AddDays(NumWeeks * 7); StartDate = BaseDate; while (StartDate. DayOfWeek != DayOfWeek.
Creating a DateTime ObjectBy assigning the DateTime object a date and time value returned by a property or method. By parsing the string representation of a date and time value. By calling the DateTime structure's implicit default constructor.
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
Edit: Updated the answer to allow a startdate (optional).
Get next friday:
Dim NextFriday As Date = GetNext(DayOfWeek.Friday)
What is the next friday after 15 days from now:
Dim AnotherFriday As Date = GetNext(DayOfWeek.Friday,now.addays(15))
'
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With