Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the week number of a given date in Visual Basic 6?

Has anyone a working function that returns the week number of a given date in vb6?

This used to work:

Dim W As Integer

W = Format(DateSerial(2010, 1, 1), "ww", vbMonday, vbFirstFourDays)

But in Windows 8.1 you now get "Out of stack space".

like image 438
fiffens Avatar asked Feb 10 '14 22:02

fiffens


1 Answers

The answer is a bit more complex given the offsets

The following function should work well for what you need. Simply pass it a valid Date object, and it will return an Integer of the Week number.

Private Function Week(dteValue As Date) As Integer
   'Monday is set as first day of week
   Dim lngDate As Long
   Dim intWeek As Integer

   'If january 1. is later then thursday, january 1. is not in week 1
   If Not Weekday("01/01/" & Year(dteValue), vbMonday) > 4 Then
      intWeek = 1
   Else
      intWeek = 0
   End If
   'Sets long-value for january 1.
   lngDate = CLng(CDate("01/01/" & Year(dteValue)))

   'Finds the first monday of year
   lngDate = lngDate + (8 - Weekday("01/01/" & Year(dteValue), vbMonday))
   'Increases week by week until set date is passed
   While Not lngDate > CLng(CDate(dteValue))
      intWeek = intWeek + 1
      lngDate = lngDate + 7
   Wend
   'If the date set is not in week 1, this finds latest week previous year
   If intWeek = 0 Then
      intWeek = Week("31/12/" & Year(dteValue) - 1)
   End If
   Week = intWeek
End Function

This code is courtesy of FreeVBCode.com (included a reference to give attribute to the original author).

like image 81
Kraang Prime Avatar answered Nov 12 '22 08:11

Kraang Prime