【问题标题】:Convert string (with UTC) to DateTime [duplicate]将字符串(使用 UTC)转换为 DateTime [重复]
【发布时间】:2012-10-09 14:17:32
【问题描述】:

可能重复:
DateTime.ParseExact format string

如何将字符串转换为 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
}

【问题讨论】:

标签: c# asp.net-mvc-3 jquery


【解决方案1】:

我建议您在您的 javascript Date 实例上使用 .toJSON() 方法,以便将它们序列化为 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
}

【讨论】:

  • 非常感谢@Darin Dimitrov。我真的为此苦苦挣扎了很久。
【解决方案2】:

试试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 了解更多示例。

【讨论】:

  • 仍然收到此错误“字符串未被识别为有效的日期时间。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 2013-03-03
  • 2014-01-15
  • 1970-01-01
相关资源
最近更新 更多