2017-06-13 55 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 - 当然是。非常马虎:-) –

相关问题