原始 JavaScript 日期到 VB.net 日期时间

Raw javascript date to VB.net datetime

本文关键字:日期 net 时间 VB JavaScript 原始      更新时间:2023-09-26

我有一个javascript AJAX调用,将javascript日期对象传递给 ASP.Net MVC控制器。下面是 AJAX 调用:

  var timestamp = new Date();
  $.ajax({
    url: '',
    type: 'POST',
    data: { username: username,
            timestamp: timestamp,
            hash: ''},
    dataType: 'json',

(我省略了一些敏感值,但重要的部分就在那里)。

控制器有一个用于正在传递的参数的对象,该对象可以很好地填充。

Public Class AjaxParams
   Public Property Username As String
   Public Property Hash As String
   Public Property Timestamp As String
End Class

下面是控制器声明:

<HttpPost()> _
Public Function RetrieveSalt(params As AjaxParams)

调用控制器时,所有参数都会正确传递并填充 AjaxParams 对象。

但是,稍后在我的代码中,我将尝试将传递的 javascript 日期从其字符串表示转换为 VB.net DateTime 对象。我创建了一个函数来执行此操作,该函数在某些日期上工作正常,但它根本不够强大,无法转换所有必要的日期格式,并且在许多日期上失败。

以下是必须转换的失败日期格式之一:

星期二 九月 17 2013 07:01:36 GMT+0600 (ALMT)

这是我创建的函数:

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 'GMT'zzzz '(BST)'", _
                               "ddd MMM d yyyy HH:mm:ss 'GMT'zzzz '(GMT)'", _
                               "ddd MMM d yyyy HH:mm:ss 'GMT'zzzz", _
                               "ddd MMM d yyyy HH:mm:ss 'UTC'zzzz"}
    ' Ensure no leading or trailing spaces exist
    dDate = dDate.Trim(" ")
    Select Case True
        Case IsNumeric(dDate)
            Dim Unix_Date As Long = Long.Parse(dDate)
            Try
                Dim newDate As Date = New DateTime(1970, 1, 1, 0, 0, 0, 0)
                Converted_Date = newDate.AddMilliseconds(Unix_Date)
            Catch ex As Exception
                Converted_Date = Nothing
            End Try
        Case Else
            Try
                Converted_Date = JsonConvert.SerializeObject(dDate)
            Catch ex As Exception
                ' Find the location of the first opening bracket
                Dim OpeningBracket As Integer = dDate.IndexOf("(")
                Dim DateLength As Integer = dDate.Length
                ' Remove the trailing timezone abbreviation in brackets
                dDate = dDate.Remove(OpeningBracket, DateLength - OpeningBracket)
                ' 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
            End Try
    End Select
    Return Converted_Date
End Function

要么我在这里错过了一些非常简单的东西,要么将日期格式解析为带有时区信息的 DateTime 对象等真的很痛苦。

有没有人对如何最好地实现这一目标有任何想法?

最简单的方法是将 JavaScript 更改为:

...
timestamp: timestamp.toISOString(),
...

这将发出 ISO-8601 格式的 UTC 日期和时间,例如:"2013-09-17T19:40:07.057Z"

但是,这并非在所有浏览器中完全实现。 如果你想与旧的浏览器完全兼容,那么你要么需要这里的垫片,要么考虑使用moment.js。

...
timestamp: moment(timestamp).toISOString(),
...

在 .NET 端,分析已经为你提供。

Dim dt As DateTime
dt = DateTime.Parse("2013-09-17T19:40:07.057Z", _
               CultureInfo.InvariantCulture, _
               DateTimeStyles.RoundtripKind)

有些人喜欢的另一种方法是只传递Date.getTime()的整数,然后将其添加到new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc)。 我宁愿避免这种情况,因为整数不如 ISO 格式可读。

还要考虑,您尝试解析的确切字符串格式因浏览器和区域设置而异。 这种方法不受此影响。