Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET - Given a date, how can I get the date of the following friday?

Given a Date, how can I get the date of following Friday (or any other weekday) in VB.NET in .NET Framework 2.0?

like image 847
Cochabambinito Avatar asked Jun 27 '11 14:06

Cochabambinito


People also ask

How to get the day of the week in VB net?

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.

How to display Date in VB net?

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.

How do I get a week start date and end date in VB net?

int NumWeeks = 30; DateTime StartDate, EndDate; DateTime BaseDate = new DateTime(2010, 1, 1); BaseDate = BaseDate. AddDays(NumWeeks * 7); StartDate = BaseDate; while (StartDate. DayOfWeek != DayOfWeek.

How to declare DateTime in VB net?

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.


3 Answers

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))
like image 75
Stefan Avatar answered Nov 15 '22 07:11

Stefan


'
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
like image 27
dbasnett Avatar answered Nov 15 '22 07:11

dbasnett


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)
like image 26
Bala R Avatar answered Nov 15 '22 08:11

Bala R