Admin
Admin

Reputation: 193

parse date string with date format in winform .net

I am using vb.net, framework 3.5 and winform application. I am loading records from database which contains date as Text string :

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

for parsing date,I am using :

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

Is there any better way to parse these similar type of format and get Exact date ?

Upvotes: 0

Views: 571

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82524

If you don't want to limit the dates to specific formats, then go with RBT's answer. However, if you want to limit the dates to the specified formats, you should use the TryParseExact method of the DateTime struct:

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

Please note that this function return type is nullable(of date) and not date.

Upvotes: 2

RBT
RBT

Reputation: 25955

No need to put so many if-else blocks where you are trying to match it against various possible patterns using ParseExact API. I would rather suggest you to go straightaway with TryParse API and it will do the needful for you. Have a look at the below code snippet. That way you will also be able to avoid so many try-catch blocks:

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

Upvotes: 1

Related Questions