首页 文章

通过知道星期和日期而不是日期来获取vb.net中的日期

提问于
浏览
1
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

1 回答

  • 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 方法正确解析字符串 .

相关问题