2012-10-09 188 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。” –