2017-01-08 7 views
0

私はvb.netフレームワーク3.5とwinformアプリケーションを使用しています。私が使用しています、日付を解析するため日付形式の日付文字列をwinformで解析する。

4/5/2016  (d/M/yyyy) ' 4th May 2016 
06/05/2016 (dd/MM/yyyy) ' 6th May 2016 
05/8/2016 (dd/M/yyyy) ' 5th August 2016 
6/08/2016 (d/MM/yyyy) ' 6th August 2016 

:私は、テキスト文字列として日付を含むデータベースからレコードをロードしています

Public Function GetDate(ByVal DateTxt As String) As Date 
    Dim date_ As Nullable(Of Date) = Nothing 
    Try 
     date_ = DateTime.ParseExact(DateTxt, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture) 
    Catch ex As Exception 
    End Try 
    If date_ Is Nothing Then 
     Try 
     date_ = DateTime.ParseExact(DateTxt, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture) 
     Catch ex As Exception 
     End Try 
    End If 
    If date_ Is Nothing Then 
     Try 
     date_ = DateTime.ParseExact(DateTxt, "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture) 
     Catch ex As Exception 
     End Try 
    End If 
    If date_ Is Nothing Then 
     Try 
     date_ = DateTime.ParseExact(DateTxt, "d/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture) 
     Catch ex As Exception 
     End Try 
    End If 
    Return date_ 
End Function 

のフォーマットのこれらの同様のタイプを解析し、正確な取得する任意のより良い方法はあります日付?

+1

[SSISはさまざまな形式の文字列日付をDateTimeに変換できます](http://stackoverflow.com/questions/40441398/ssis-convert-string-date-with-various-formats-to-datetime) – Hadi

+0

VB.NETでコーディングしているので、関係のないC#タグは使用しないでください。 – Bugs

+0

'テキストを文字列として含むデータベース'があります。 – Plutonix

答えて

2

日付を特定の形式に制限したくない場合は、RBTの回答に進んでください。

Public Function GetDate(ByVal DateTxt As String) As Nullable(Of Date) 
    Dim date_ As Date 
    Dim AcceptableFormats As String() = {"dd/MM/yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy"} 
    If Not DateTime.TryParseExact(DateTxt, AcceptableFormats, System.Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, date_) Then 
     Return Nothing 
    End If 

    Return date_ 
End Function 

は、この関数の戻り値の型がnullable(of date)ないdateであることに注意してください:あなたが指定した形式に日付を制限したい場合は、DateTime構造体のTryParseExact方法を使用する必要があります。

1

多くのif-elseブロックを、ParseExact APIを使用して、さまざまな可能なパターンと照合しようとする場所に配置する必要はありません。私はむしろTryParse APIですぐに行くことを提案し、それはあなたのために必要な作業を行います。以下のコードスニペットを見てください。そうすれば、多くのtry-catchブロックを避けることもできます:

Public Function GetDate(ByVal DateTxt As String) As Date 
    Dim date_ As Nullable(Of System.DateTime) = Nothing 
    DateTime.TryParse(DateTxt, date_) 
    Return date_ 
End Function 
関連する問題