我有一个 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 对象。我创建了一个函数来执行此操作,该函数对于某些日期可以正常工作,但它根本不够强大,无法转换所有必要的日期格式,并且在许多日期上都失败了。
这是必须转换的失败日期格式之一:
2013 年 9 月 17 日星期二 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 对象,这真的很痛苦。
有没有人对如何最好地做到这一点有任何想法?