Hi Guys,

in vb we can get the week number counting from January. ex Jan 1st is Week 1 and Feb 1st is Week 5 etc by

DatePart(DateInterval.WeekOfYear, Now)

I need to count the week number from a given date. ex: if set the base to July 1st then July 1st is the week 1 and based on that what would be the week number for Oct 3rd? How can I do this in VB?

Dani AI

Generated

Two useful interpretations of "week number from a given date" are: (A) treat the chosen base date as the start of week 1 (Jul 1 => week 1), or (B) align weeks to a standard week boundary (e.g., Mondays) while using the base as a fiscal-year anchor. and were on the right track by counting days; the snippet below gives a concise, robust VB.NET implementation for interpretation (A), with an option to wrap dates that fall before the base into the next year.

Private Function WeekNumberFromBase(baseDate As DateTime, targetDate As DateTime, Optional wrapToNextYear As Boolean = False) As Integer
    Dim b As DateTime = baseDate.Date
    Dim t As DateTime = targetDate.Date

    If wrapToNextYear AndAlso t < b Then
        t = t.AddYears(1)
    End If

    Dim daysDiff As Long = DateDiff(DateInterval.Day, b, t)    ' full-day difference
    If daysDiff < 0 Then
        Return 0   ' indicates target is before base (choose alternate behavior if preferred)
    End If

    Dim weeksElapsed As Integer = CInt(daysDiff \ 7)   ' integer division
    Return weeksElapsed + 1
End Function

Example: with base = 2012-07-01 and target = 2012-10-03 this returns 14 (Jul 1 is week 1). Notes: the function counts partial first week as week 1; set wrapToNextYear = True to treat dates earlier in the calendar year as belonging to the following fiscal year; strip time-of-day (use .Date) to avoid off-by-one problems; to instead align weeks to a weekday, normalize the base back to that weekday before calling this routine.

Recommended Answers

All 3 Replies

Kind of simplistic, but you can try something like this;

Private Function WeekOfYear(ByVal dt As Date) As Integer
    Try
        Return dt.DayOfYear / 7
    Catch ex As Exception
        MsgBox("There was a problem retreiving the week of the year!" & vbCrLf & ex.Message)
        Return Nothing
    End Try
End Function

See if this works for your needs:

Private Function WeeksNumFromBasis(ByVal basis As DateTime, ByVal SubjectDate As DateTime) As Double
   Return SubjectDate.Subtract(basis).TotalDays / 7
End Function

Thank you all for your replies and sorry for late to reply. I was able to find excel

formula that suit my need when searching. Now I need to convert that into vb code

please help me on this.

INT((A2-DATE(YEAR(A2+92)-1,10,1)-WEEKDAY(A2))/7)+2

A2 is a any given date.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.