Dim x As Date
x = "5/26/2011"
Dim whichweek As Double = x.DayOfYear / 7
Dim whichday As Integer = x.DayOfWeek
使用此信息我可以获得去年的某一周和该周的某一天并使用日期
这是返回2010年4月10日而不是4/5/2010,2011年5月26日将返回2011年5月27日
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(whichweek * 7 + whichday, 0, 0, 0)
Dim sameWeekLastYear = New DateTime(x.Year - 1, 1, 1) + offset
Label9.Text = sameWeekLastYear
答案 0 :(得分:2)
要在上一年的同一周获得相同的工作日,您可以使用以下内容:
Dim offset As New TimeSpan(whichweek * 7 + whichday, 0, 0, 0)
Dim sameWeekLastYear = New DateTime(x.Year - 1, 1, 1) + offset
(但正如汉斯在评论中所说,不幸的是,你对本周的计算是错误的。)
但是,请勿使用字符串初始化日期。实际上,您的代码甚至不应该编译。您应该启用Option Strict
以使编译器更严格地检查错误。
要从常量初始化日期,请使用日期文字语法:
Dim date = #5/26/2011#
或者,如果您确实需要来读取字符串,因为您正在读取文件或获取用户输入,请使用DateTime.Parse
方法正确解析字符串。