2017-06-13 6 views
-1

特定の文字列をdatetimeに分解する必要があります。この文字列は、以下に示すように、カンマとアンパサンドを使用する構文を特定の方法で使用します。文字列を「5月23日、24日、25日および26日」を別々のDateTimesに変換する

文字列"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を使用している場合、01の代わりにparams(i)を使用してmonthNumberを削除できますか? –

+0

はい、私はこのソリューションが好きですが、上記のコメントに同意します。 Dim monthNumberは、質問の例に基づいてループの外側に置くことができます:) –

+0

Duh - もちろんです。私は非常にうんざりしています:-) –

関連する問題