Dim x As Date
x = "5/26/2011"
Dim whichweek As Double = x.DayOfYear / 7
Dim whichday As Integer = x.DayOfWeek
using this information could i get a certain week last year and a certain day of that week and use the date
This is return 4/10/2010 instead of 4/5/2010 and 5/26/2011 is returning 5/27/2011
Public Shared Function GetWeekNumber(ByVal dtPassed As DateTime) As Integer
Dim ciCurr As CultureInfo = CultureInfo.CurrentCulture
Dim weekNum As Integer = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)
Return weekNum
End Function
Dim x As Date
x = "4/04/2011"
Dim whichweek As Integer = GetWeekNumber(x.Date)
Dim whichday As Integer = x.DayOfWeek
Dim offset As New TimeSpan(w开发者_如何学编程hichweek * 7 + whichday, 0, 0, 0)
Dim sameWeekLastYear = New DateTime(x.Year - 1, 1, 1) + offset
Label9.Text = sameWeekLastYear
To get the same weekday in the same week of the previous year, you can use something like this:
Dim offset As New TimeSpan(whichweek * 7 + whichday, 0, 0, 0)
Dim sameWeekLastYear = New DateTime(x.Year - 1, 1, 1) + offset
(But as Hans said in the comments, your calculation of the week is unfortunately wrong.)
However, don’t use a string to initialise a date. In fact, your code shouldn’t even compile. You should enable Option Strict
to make the compiler check for errors more strictly.
To initialise a date from a constant, use the date literal syntax:
Dim date = #5/26/2011#
Or, if you really need to read a string because you’re reading a file or getting user input, use the DateTime.Parse
method to parse the string properly.
精彩评论