itay312
itay312

Reputation: 1568

vb.net add one week to a given date

I am trying to add one week to a given date using an extension method and then retrieve the date of the first day in the week (of the date returned from the AddWeeks function)

Private Sub doSomething()
  Dim dt As DateTime = DateTime.Now.AddWeeks(1)

  dt = dt.StartOfWeek(dt.DayOfWeek) ' The year returned here is 0001
End Sub

<Extension()>
    Public Function AddWeeks(ByVal dt As DateTime, numOfWeeks As Integer) As 
    DateTime
        Return dt.AddDays(numOfWeeks * 7)
End Function
<Extension()>



    <Extension()>
Public Function StartOfWeek(ByVal dt As DateTime, start As DayOfWeek) As DateTime
    Dim diff As Integer = dt.DayOfWeek - start
    If (diff < 0) Then
        diff += 7
    End If

    Return dt.AddDays(-diff)
End Function

The problem with this code is that the date returned is is with wrong year, it is always like dd/mm/0001

Upvotes: 1

Views: 1266

Answers (1)

user6120842
user6120842

Reputation:

To get to the first day of the week try deducting a day until you get to Monday like this:

Public Function StartOfWeek(ByVal dt As DateTime, start As DayOfWeek) As DateTime

    If Not dt.DayOfWeek = DayOfWeek.Monday Then

        While dt.DayOfWeek <> DayOfWeek.Monday

            dt = dt.AddDays(-1)

        End While

    End If

    Return dt

End Fuction

Upvotes: 1

Related Questions