特殊日期格式化字符串到日期(VB.net)

时间:2014-01-08 10:34:32

标签: vb.net date date-format date-conversion

如果我有一个包含日期格式的字符串:

1402-3

表示年份:2014年,周:02和第3天(星期一是1),如何将此转换为正常日期? (在这种情况下,上面的日期是今天; 2014-01-08 - 2014年1月8日星期三)

编辑:我想出了这样的功能,有人能说出这是否会失败或者是否有更好更好的编码功能/解决方案?

Private Function StrangeFormattedDateToRegularDate(ByVal StrangeDate As String) As Date
    Dim Y As String = "20" & StrangeDate.Substring(0, 2) 'I'll be dead before this fails, haters gonna hate
    Dim W As String = StrangeDate.Substring(2, 2)
    Dim D As String = StrangeDate.Substring(5, 1)

    'Get first day of this year
    Dim RefDate As Date = New Date(CInt(Y), 1, 1)

    'Get the first day of this week (can be the year before)
    Dim daysOffSet As Integer = DayOfWeek.Monday - RefDate.DayOfWeek
    RefDate = RefDate.AddDays(daysOffSet)

    'Add as many days as the weeks is
    RefDate = RefDate.AddDays(7 * CInt(W))

    'now the date is the last day of this week (plus one day), remove the days that are ahead, and remove that extra day
    Dim daysToRemove = ((7 - CInt(D)) * -1) - 1
    RefDate = RefDate.AddDays(daysToRemove)

    Return RefDate
End Function

1 个答案:

答案 0 :(得分:1)

这应该是你正在寻找的:)这看起来很有挑战性,所以我尝试了。告诉我它是否适合你:)

 Function GetDate(InputDate As String) As DateTime
    Dim FirstDayofYear As Date = CType("1/1/20" & Mid(InputDate, 1, 2), Date)
    Dim LastDayofYear As Date = CType("12/31/20" & Mid(InputDate, 1, 2), Date)
    Dim target As Date
    For x = 0 To DateDiff(DateInterval.Day, FirstDayofYear, LastDayofYear)
        Dim dfi = DateTimeFormatInfo.CurrentInfo
        Dim calendar = dfi.Calendar
        Dim weekOfyear = calendar.GetWeekOfYear(FirstDayofYear.AddDays(x), dfi.CalendarWeekRule, DayOfWeek.Sunday)
        If CInt(Mid(InputDate, 3, 2)) = weekOfyear And CInt(Mid(InputDate, InStr(InputDate, "-") + 1)) = FirstDayofYear.AddDays(x).DayOfWeek Then
            target = FirstDayofYear.AddDays(x)
            GoTo skip
        End If
    Next x
skip:
    Return target
End Function

这可以到2099年。到那时我们可能都死了。