我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:

return new JsonResult(myModel);

这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:

"\/Date(1239018869048)\/"

我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?


当前回答

Ajax communication between the client and the server often involves data in JSON format. While JSON works well for strings, numbers and Booleans it can pose some difficulties for dates due to the way ASP.NET serializes them. As it doesn't have any special representation for dates, they are serialized as plain strings. As a solution the default serialization mechanism of ASP.NET Web Forms and MVC serializes dates in a special form - /Date(ticks)/- where ticks is the number of milliseconds since 1 January 1970.

这个问题有两种解决方法:

客户端

将接收到的日期字符串转换为数字,并使用日期类的构造函数以tick为参数创建日期对象。

function ToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}

服务器端

前面的解决方案使用客户端脚本将日期转换为JavaScript date对象。您还可以使用服务器端代码以您选择的格式序列化. net DateTime实例。 要完成这个任务,你需要创建自己的ActionResult,然后以你想要的方式序列化数据。

参考: http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html

其他回答

我有同样的问题,而不是返回实际的日期值,我只是使用ToString(“dd MMM yyyy”)。然后在我的javascript中,我使用了新的日期(datevalue),其中datevalue可能是“01 Jan 2009”。

重写控制器Json/JsonResult以返回Json。Net:

这很有用

这不是最优雅的方式,但对我来说很管用:

var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);


function formatDate(ms) {

    var date = new Date(parseInt(ms));
    var hour = date.getHours();
    var mins = date.getMinutes() + '';
    var time = "AM";

    // find time 
    if (hour >= 12) {
        time = "PM";
    }
    // fix hours format
    if (hour > 12) {
        hour -= 12;
    }
    else if (hour == 0) {
        hour = 12;
    }
    // fix minutes format
    if (mins.length == 1) {
        mins = "0" + mins;
    }
    // return formatted date time string
    return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}

最简单的一个:

var milisegundos = parseInt(data.replace(“/Date(”, “”).replace(“)/”, “”)); Var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

js是一个扩展的datetime库,它也支持这个功能。http://momentjs.com/docs/#/parsing/asp-net-json-dates/

ex - Date(1198908717056-0700):时刻(“”)

这可能会有帮助。恰好输出