Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the week number of the year counting from a given date in VB

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?

like image 593
user1717576 Avatar asked Oct 03 '12 15:10

user1717576


2 Answers

You can use Calendar.GetWeekOfYear.

Here's an example

Dim dateNow = DateTime.Now
Dim dfi = DateTimeFormatInfo.CurrentInfo
Dim calendar = dfi.Calendar

' using Thursday because I can.
Dim weekOfyear = calendar.GetWeekOfYear(
    dateNow, _
    dfi.CalendarWeekRule, _
    DayOfWeek.Thursday) 
like image 115
Jodrell Avatar answered Nov 21 '22 16:11

Jodrell


Something like this should do the trick:

Private Function GetWeekNumber(ByVal startMonth As Integer, ByVal startDay As Integer, ByVal endDate As Date) As Integer
    Dim span As TimeSpan = endDate - New Date(endDate.Year, startMonth, startDay)
    Return (CInt(span.TotalDays) \ 7) + 1
End Function
like image 33
Steven Doggart Avatar answered Nov 21 '22 15:11

Steven Doggart