J-J J-J - 4 months ago 47x
Vb.net Question

How to get starting date in a Week based on week number using vb.net?

I need help on getting the starting date of a week from a given week number in vb.net.

I have combobox binded with items 1-53 as week numbers. What I want to do is whenever I select a specific week number, it will return the first date of that selected week number.

For instance I have selected week Number 46, it must return November 11, 2013 as first date of week number 46.

I have tried the following codes and it returns only the first date of a week from a current week number.

DateAdd("d", -Weekday(Now, FirstDayOfWeek.Monday) + 1, Now)

Is there any possible way that can return my expected output?

Please help me. Thanks in advance.


You could try something like this:

Private Sub TestDateAdd()
    Dim weekStart As DateTime = GetWeekStartDate(46, 2013)
End Sub

Private Function GetWeekStartDate(weekNumber As Integer, year As Integer) As Date
    Dim startDate As New DateTime(year, 1, 1)
    Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber - 1, startDate)
    Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate)
End Function

Disclaimer: I only really tested this with the one input, you probably want to make sure that it works as expected for different years, etc..