Search code examples
vb.netdateregion

Error converting string to Custom Date Format


In my application I got error when trying to convert a Date from string date format as shown below:

dateFormat = Format(CDate("2014-mar-06"), "MM/dd/yyyy")

Error

Conversion from string "2014-mar-06" to type 'Date' is not valid

This problem only comes when my Region and Language setting is Spanish(Mexico) (or any spanish but not for others) in Windows 7 . What is the problem and how to solve this?


Solution

  • Avoid VB6 functions like CType and use .NET methods like TryParse instead. Also CultureInfo.InvariantCulture gets the CultureInfo object that is culture-independent (invariant)

    Try this

        Dim dateString = "2014-mar-06"
        Dim dateValue As DateTime
    
        If DateTime.TryParseExact(dateString, _
            "yyyy-MMM-dd", CultureInfo.InvariantCulture, _
            DateTimeStyles.None, dateValue) Then
    
            Dim myDate = dateValue.ToString("MM/dd/yyyy") 'Your Date is stored in myDate
    
        Else
            'Unable to parse your dateString
        End If