Any function can return the date (bypassing weeknumber,weekyday) ?

  • Thread starter Thread starter Agnes
  • Start date Start date
A

Agnes

Does .net provide any function for such purpose ?
e.g today is 21-10-2004, the week is 43, now I want to get the DATE with
(week 42, Monday)
Thanks alot
 
Agnes,
You can use DateTime.AddDays(7) to add a week or AddDays(-7) to subtract a
week from a specific date.

Dim today As DateTime = #10/21/2004#
lastWeek = today.AddDays(7)

If you want to adjust a date to a specific day of week you can use something
like:

Private Shared Function FirstDayOfWeek(ByVal day As DateTime, ByVal
weekStarts As DayOfWeek) As DateTime
Return day.AddDays(weekStarts - day.DayOfWeek)
End Function

Public Shared Sub Main()
Dim today As DateTime = #10/21/2004#
Dim lastWeek As DateTime = today.AddDays(-7)
Dim nextWeek As DateTime = today.AddDays(7)

Dim lastMonday As DateTime = FirstDayOfWeek(lastWeek,
DayOfWeek.Monday)
Dim nextMonday As DateTime = FirstDayOfWeek(nextWeek,
DayOfWeek.Monday)

Debug.WriteLine(today, "today")
Debug.WriteLine(lastWeek, "last week")
Debug.WriteLine(lastMonday, "last monday")
Debug.WriteLine(nextWeek, "next week")
Debug.WriteLine(nextMonday, "next monday")
End Sub

If you want to find a date in a specific week of the year you can use:

Public Function GetDateFromWeek(ByVal year As Integer, _
ByVal week As Integer, _
ByVal dayOfweek As DayOfWeek) Ad Date

Dim firstOfYear As New Date(year, 1, 1)

Return firstOfYear.AddDays((week - 1) * 7 + dayOfWeek _
- firstOfYear.DayOfWeek)

End Function

Then you can call it as:

Dim week As Date
week = GetDateFromWeek(2004, 42, DayOfWeek.Monday)

I will leave calculating the Week Of Year function for you.

Remember that Date is simply an alias for DateTime.

Hope this helps
Jay
 
Thanks Jay,
I know how to write a function 'week of year' , so I try to combine your
code . Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top