Reputation: 1113
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.
Upvotes: 2
Views: 17095
Reputation: 31
Public Function FirstDateOfWeek(ByVal Year As Integer, ByVal Week As Integer, Optional FirstDayOfWeek As DayOfWeek = DayOfWeek.Monday) As Date
Dim dt As Date = New Date(Year, 1, 1)
If dt.DayOfWeek > 4 Then dt = dt.AddDays(7 - dt.DayOfWeek) Else dt = dt.AddDays(-dt.DayOfWeek)
dt = dt.AddDays(FirstDayOfWeek)
Return dt.AddDays(7 * (Week - 1))
End Function
Upvotes: 3
Reputation: 191
You could try something like this:
Private Sub TestDateAdd()
Dim weekStart As DateTime = GetWeekStartDate(46, 2013)
Console.WriteLine(weekStart)
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..
Upvotes: 2