Link to home
Start Free TrialLog in
Avatar of Nolanc
Nolanc

asked on

Convert Date From dd/MM/yyyy Format To MM/dd/yyyy Format in VB.NET

Hi

I have the following Function in my application:

Public Function ToSqlDate(ByVal PassDate As Date) As Date
       Return Date.Parse(PassDate.Month.ToString & "/" & PassDate.Day.ToString & "/" & PassDate.Year.ToString)
End Function

I call the function as follows:

SqlStart = ToSqlDate(StartDate) Where SqlStart has DataType "Date" and StartDate is a date value in a DateTimePicker Control.

When I run the application it abends with a message "String Was Not Recognised As Valid DateTime).

At this point in time when I hover the mouse over PassDate it displays a value of #9/30/2010# whereas I passed a value of 30/09/2010.

My Regional Setting for date is dd/MM/yyyyy.

The reason I must convert the Date to MM/dd/yyyy is that SQL requires it in this format in order to make comparisons with dates.

Any ideas or recommendations how I can get around this problem.

Thanks
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

SqlStart = StartDate.ToString("dd/MM/yyyy",CultureInfo.InvariantCulture)


http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Try the below code in cs and in db convert the date field to the required format
In the below code you can pass your DateFormat() i.e mm/dd /yyyy or dd/mm/yyyy
 Protected Function GetStartDate(ByVal dtStartDate As DateTime) As String
        Dim strStartDate As String = String.Empty
        If (dtStartDate <> DateTime.MinValue) Then
            strStartDate = dtStartDate.ToString(DateFormat())
        Else
            strStartDate = DateTime.Now.ToString(DateFormat())
        End If
        Return strStartDate
    End Function

or 

    Private Function GetDate(ByVal strDate As String) As DateTime
        Dim objCultureInfo As CultureInfo = New CultureInfo(sHdnCurrentCulture.Value)
        Dim dtDate As DateTime
        If strDate <> String.Empty Then
            dtDate = DateTime.ParseExact(strDate, DateFormat(), objCultureInfo.DateTimeFormat)
            Return dtDate

        End If
    End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nolanc
Nolanc

ASKER

Excellent advice. Thank you.