私は、JavaScript日付オブジェクトをASP.Net MVCコントローラーに渡すJavaScript AJAX呼び出しを持っています。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 オブジェクトに変換しようとしています。これを行うための関数を作成しましたが、これは一部の日付では正常に機能しますが、必要なすべての日付形式を変換するには十分に堅牢ではなく、多くの日付で失敗しています。
変換する必要がある失敗した日付形式の 1 つを次に示します。
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 オブジェクトに解析するなどは本当に面倒です。
これを達成するための最善の方法について誰かアイデアがありますか??