转换字符串" 5月23日,24日,25日& 26"分开的DateTimes

时间:2017-06-13 13:35:32

标签: vb.net loops datetime

我需要将给定的字符串分解为datetime(s)。该字符串使用逗号和符号的语法,具体方式如下所示。

字符串"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}

1 个答案:

答案 0 :(得分: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