Get date range for a week.

  • Thread starter Thread starter Hetal
  • Start date Start date
H

Hetal

I am working on Visual Basic 2003 and i had a question about date
functions. Is there a way to get the date range for a week based on
the combination of 1) Week of the year and 2) Year? I mean, is there a
VB function where i can pass the week of the year and current year and
get the date range that fall under that week?

Thanks,
Hetal.
 
Basically, no - you need to write your own.

The thing you need to define clearly how you determine is what constitutes
the first week of any given year and also what day is the first day of the
week.

There are are a number of so called standards for this and not everyone
agrees on which is correct or which is best.

The one that seems to be most prevalent for the Gregorian calendar is that
the first day of the week is Monday and week 1 is the first week where the
1st of January falls on a Monday, Tuesday, Wednesday or Thursday, (i.e, the
first week of January where 4 or more days fall in January).

The basic logic is as follows:

The first thing to compute is the start date for week 1 for a given year.

Dim _year As Integer = 2007

Dim _date As New DateTime(_year, 1, 1)

Dim _day As DayOfWeek = _date.DayOfWeek

Dim _start As DateTime

Select Case _day
Case DayOfWeek.Sunday
' Special case because DayOfWeek.Sunday = 0
_start = _date.AddDays(1)
Case Is < DayOfWeek.Thursday
' Week does not have 4 days in January so advance to Monday of next
week
_start = _date.AddDays(DayOfWeek.Monday - _day + 7)
Case Else
' Week has 4 days in January so retreat to Monday of this week
_start = _date.AddDays(DayOfWeek.Monday - _day)
End If

Dim _week As Integer = 1

Dim _rangeforweek1 as DateTime() = New DateTime() {_start,
_start.AddDays(6)}

This done, you need to compute the range for the week of interest.

Dim _weekofinterest = 24

Dim _rangeforweekofinterest as DateTime() = New DateTime()
{_start.AddDays((_weekofinterest - 1) * 7),
_start.AddDays((_weekofinterest - 1) * 7 + 6)}

You also need to take into account the vagary where, if the 31st of December
falls on a Monday, Tuesday or Wednesday then, for that year, the last 1, 2
or 3 days(s) respectively fall in week 1 of the following year.

Work the bones of that into a function to suit you and you should get the
results you require.
 
Hi Stephany,

This information will be a good base for me to work out the logic that
i need for my date requirements. Really appreciate your help on this
one.

Thank you,
Hetal.
 
Back
Top