在VB中将日期,周数和年份转换为日期

时间:2018-06-04 18:08:32

标签: vb.net

我需要帮助转换年份,周数和日期。因此,如果date1是1990,则wN是12,dDay是3,结果应该是3/21/1990(mm / dd / yyyy格式)。

我在找到正确的格式时遇到问题:Output(Date(date1, 1, 1) + ((wN - 1) * 7) - Weekday(Date(date1, 1, 1) + (wN - 1) * 7, 2) + 1 + (dDay - 1))

此代码在Excel中运行良好。我试图将其转换为在vb.net中工作

    Dim str1 As String = txtInput1.Text
    Dim d2 As String
    Dim date1 As Integer
    Dim date2 As Integer
    Dim wN As Integer
    Dim dDay As Integer

    Dim cYear As Integer = DateTime.Now.Year

    txtOutput.Text = ""

    d2 = Mid(str1, 2, 1)
    wN = Mid(str1, 3, 2)
    dDay = Mid(str1, 5, 1)

    If d2 = "G" Then
        date1 = 1990
        date2 = 2013
        If date2 <= cYear Then
            'Output("Year Built " & date1 & " or " & date2 & vbCrLf & "Week " & wN & vbCrLf & "Day " & dDay)
            Output(Date(date1, 1, 1) + ((wN - 1) * 7) - Weekday(Date(date1, 1, 1) + (wN - 1) * 7, 2) + 1 + (dDay - 1))
        Else
            Output("Year Built " & date1)
        End If

1 个答案:

答案 0 :(得分:1)

你的公式有点偏。从年初开始,添加天数。

    Const DAYS_IN_A_WEEK As Integer = 7

    Dim year As Integer = 1990
    Dim weekNumber As Integer = 12
    Dim dayOfWeek As Integer = 3

    Dim calculatedDate = New DateTime(year, 1, 1)
    calculatedDate = calculatedDate.AddDays((weekNumber - 1) * DAYS_IN_A_WEEK + (dayOfWeek - 1) - (CInt(calculatedDate.DayOfWeek) - 1))