2012-10-09 190 views
1

可能重複:
DateTime.ParseExact format string將字符串轉換(與UTC)爲DateTime

如何將字符串轉換爲DateTime對象?

例子:

太陽2012年10月7日00:00:00 GMT + 0500(巴基斯坦標準時間)

我都試過了,DateTime.Parse,Convert.TODateTime等無工作。我得到一個錯誤,它不是一個有效的DateTime字符串。

這裏是如何我從jQuery的發送日期時間到MVC控制器的操作方法:

$.ajax({ 
     url: '@Url.Action("actionMethodName", "controllerName")', 
     type: "GET", 
     cache: false, 
     data: { 
       startDate: start.toLocaleString(), 
       endDate: end.toLocaleString() 
     }, 
     success: function (data) { 
     } 
}); 

我需要能夠獲得的日期時間回到控制器的操作方法:

public JsonResult actionMethodName(string startDate, string endDate) 
{ 
     if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate)) 
     { 
      var start = DateTime.Parse(startDate); //Get exception here 
      var end = DateTime.Parse(endDate);  //Get exception here 
     } 

     //Rest of the code 
} 
+6

[你有什麼試過](http://whathaveyoutried.com)?你卡在哪裏?你還有幾個其他的例子? – Oded

+2

DateTime.Parse/DateTime.TryParse –

+0

@Zdeslav Vojkovic。兩者都不起作用 –

回答

5

我會建議你使用.toJSON()方法對你的JavaScript Date情況下,以序列化它們作爲ISO 8601格式:

$.ajax({ 
    url: '@Url.Action("actionMethodName", "controllerName")', 
    type: "GET", 
    cache: false, 
    data: { 
     startDate: start.toJSON(), 
     endDate: end.toJSON() 
    }, 
    success: function (data) { 
    } 
}); 

現在你不需要在你的控制器進行解析什麼,你會直接使用日期:

public ActionResult ActionMethodName(DateTime startDate, DateTime endDate) 
{ 
    //Rest of the code 
} 
+0

非常感謝@Darin Dimitrov。我真的很爲此苦苦掙扎。 –

1

嘗試方法DateTime.ParseExact。在這個例子中,我解析了字符串的(Pakistan Standard Time)部分。

var parsedDate = DateTime.ParseExact("Sun Oct 07 2012 00:00:00 GMT+0500", 
    "ddd MMM dd yyyy hh:mm:ss 'GMT'zzz", 
    CultureInfo.InvariantCulture); 

查看these MSDN Docs的更多示例。

+0

仍然收到此錯誤「字符串未被識別爲有效的DateTime。」 –