1

我试图将作为字符串从一些 Javascript 代码传递的日期时间值转换为 VB.net 日期时间对象。

这就是我试图转换的

2012 年 9 月 27 日星期四 14:21:42 GMT+0100 (BST)

这是我到目前为止所拥有的,但转换这个日期字符串真的很困难

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

TryParse 和 TryParseExact 函数都返回 false,表示转换失败。有谁知道发生了什么事?或者更好的是,有一些代码可以成功转换日期时间字符串。有谁知道为什么这不起作用和

4

1 回答 1

2

您使用了错误的格式字符串。这是 f# 中的示例,但您应该大致了解 :-)

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

希望它会有所帮助

mz

于 2013-03-11T12:11:59.940 回答