1

Im trying to convert a datetime value passed as a string from some Javascript code into a VB.net datetime object.

This is what im trying to convert

Thu Sep 27 2012 14:21:42 GMT+0100 (BST)

And here is what I have so far but it is really struggling to convert this date string

Public Function TryParseDate(dDate As String) As Date

    Dim enUK As New CultureInfo("en-GB")
    Dim Converted_Date As Nullable(Of Date) = Nothing
    Dim Temp_Date As Date
    Dim formats() As String = {"ddd MMM d yyyy HH:mm:ss GMTzzz (BST)", _
                               "ddd MMM d yyyy HH:mm:ss GMTzzz", _
                               "ddd MMM d yyyy HH:mm:ss UTCzzz"}

    ' Ensure no leading or trailing spaces exist
    dDate = dDate.Trim(" ")

    ' Attempt standard conversion and if successful, return the date
    If Date.TryParse(dDate, Temp_Date) Then
        Converted_Date = Temp_Date
    Else
        Converted_Date = Nothing
    End If

    ' Standard date parsing function has failed, try some other formats
    If IsNothing(Converted_Date) Then
        If Date.TryParseExact(dDate, formats, enUK, DateTimeStyles.None, Temp_Date) Then
            Converted_Date = Temp_Date
        Else
            Converted_Date = Nothing
        End If
    End If

    ' Conversion has failed
    Return Converted_Date

End Function

The TryParse and TryParseExact function both return false indicating in a failed conversion. Does anyone know whats going on? Or better still, have some code that will successfully convert the datetime string. Does anyone know why this is not working and

1
  • If you have control of the Javascript code, you could use foo.toISOString() to make a string which is compliant with ISO 8601, which is quite easy to make into a DateTime object. Commented Mar 11, 2013 at 11:31

1 Answer 1

2

You're using wrong format string. Here's example in f# but you should get general idea :-)

open System
open System.Globalization

let main argv = 
    let date = "Thu Sep 27 2012 14:21:42 GMT+0100 (BST)"
    let dateparsed = DateTime.ParseExact(date, "ddd MMM dd yyyy HH:mm:ss 'GMT'zzzz '(BST)'", CultureInfo.InvariantCulture)
    printfn "%A" dateparsed
    0

Hope it'll help

mz

Sign up to request clarification or add additional context in comments.

1 Comment

Lovely, thank you...that has worked a treat. I wondered about the single quotes but wasn't 100% sure about their exact use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.