2017-06-13 62 views
-1

我需要將給定的字符串分解爲datetime(s)。該字符串以特定的方式使用逗號和連字符的語法,如下所示。將字符串「5月23,24,25和26」轉換爲單獨的日期時間

字符串"May 5"現在應該是{5/5/17}

"May 6 & 7"應該是{5/6/17, 5/7/17}

"May 20, 21 & 22"應該是{5/20/17, 5/21/17, 5/22/17}

"May 28, 29, 30 & 31"應該是{5/28/17, 5/29/17, 5/30/17, 5/31/17}

+0

你有任何示例代碼可以顯示嗎?你嘗試過嗎? –

+0

您將不得不創建自己的函數,並且如果格式始終相同,則可以簡單地使用Regex。 – Mederic

回答

1

你在這裏 - 代碼被評論來解釋幾乎所有的事情。當然唯一的問題是,如果月份名稱應該是第一個字,其餘的應該是數字值(當然除了分隔符)。

Private Function DateStringToList(Dstring As String) As List(Of Date) 
    'create a list to add converted dates to 
    Dim datelist As New List(Of Date) 
    'an array of delimiter characters to use when splitting the input string 
    Dim delimiterArray() As Char = {" "c, ","c, "&"c} 
    'split the input string into a string array, removing any blank entries 
    Dim params() As String = Dstring.Split(delimiterArray, StringSplitOptions.RemoveEmptyEntries) 
    'assign the month name from the beginning of the string to Mnth 
    Dim Mnth As String = params(0) 
    'iterate through the rest of the split elements 
    For i As Integer = 1 To params.GetUpperBound(0) 
     'workarounf to get the month number from the name - the day and year values dont matter, 
     'but you may need to change the order for your local date handling 
     Dim monthNumber = Convert.ToDateTime("01-" + Mnth + "-2000").Month 
     'create a new date based on this year, the monthNumber as the each day from the params array 
     Dim newdate As New Date(DateTime.Now.Year, monthNumber, params(i)) 
     'add the date to a list 
     datelist.Add(newdate) 
    Next 
    'Return that list to the calling code 
    Return datelist 
End Function 
+0

如果您已經在使用Convert.ToDateTime,您可以使用params(i)而不是01並刪除monthNumber嗎? –

+0

是的,我喜歡這個解決方案,但同意上面的評論。 Dim monthNumber可以在循環之外,根據問題示例:) –

+0

Duh - 當然是。非常馬虎:-) –

相關問題