2014-01-08 95 views
0

如果我有含有格式化這樣的日期的字符串:特殊日期格式化的字符串日期(VB.net)

1402-3 

這意味着年:2014,周:02和天數3(星期一是1 ),我怎樣才能將其轉換爲正常日期? (在這種情況下,上面的日期是今天; 2014-01-08 - 週三2014年1月)

編輯:我想出了這樣的功能,任何人都可以告訴如果這會失敗或可能有更好的和更好的編碼功能/解決方案

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 
+0

看看http://stackoverflow.com/questions/662379/calculate-date-from-week-number幫助。它幾乎是一個類似的問題,但在C# – saamorim

+0

嗯,它至少是我見過的最接近的答案。謝謝。 :) – gubbfett

回答

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年,我們通過那麼很可能都死了。

+0

很酷的解決方案,明天當我回到那臺電腦時,我會試一試。我可以告訴你這個解決方案,你會得到一年中的第一天,並且每天都會循環到今年的最後一天,並且每天你都會檢查「是本週02和第3天?」如果是的話,返回這個日期,如果是假的,去下一個日期?我不確定,但是這個解決方案比我上面的解決方案感覺有點慢?我喜歡你的思維方式,你的解決方案更具有失敗能力。我的例子爲我嘗試過的一些隨機日期工作,但我不知道它會工作完美的所有日期:) – gubbfett

+0

是我的朋友,它應該是技術上較慢因爲代碼最多循環365.但我不能真正告訴它是否真的很慢,因爲我沒有什麼比較。我自己製作了算法,我找不到任何接近它的地方。但循環365是非常快的,就我而言,我沒有看到任何滯後。我的解決方案可能更具有失敗的可能性,但我不知道,哪一個更適合您。任何人都可以提供比我更好的解決方案,但這是我現在最好的。只是想測試自己,並幫助其他人:) –

+0

我欣賞你的解決方案。真!明天我會試一試。我想有數百種方法可以做到這一點,如果有人提出我希望的一行解決方案,我會保持線程開放一段時間。 :)乾杯! – gubbfett