我有一个控制器动作,它有效地简单地返回模型的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

其他回答

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

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;
}

我发现创建一个新的JsonResult并返回它是不令人满意的-必须用返回新的MyJsonResult {Data = obj}替换所有返回Json(obj)的调用是一种痛苦。


所以我想,为什么不只是劫持JsonResult使用ActionFilter:

public class JsonNetFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is JsonResult == false)
        {
            return;
        }

        filterContext.Result = new JsonNetResult(
            (JsonResult)filterContext.Result);
    }

    private class JsonNetResult : JsonResult
    {
        public JsonNetResult(JsonResult jsonResult)
        {
            this.ContentEncoding = jsonResult.ContentEncoding;
            this.ContentType = jsonResult.ContentType;
            this.Data = jsonResult.Data;
            this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
            this.MaxJsonLength = jsonResult.MaxJsonLength;
            this.RecursionLimit = jsonResult.RecursionLimit;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var isMethodGet = string.Equals(
                context.HttpContext.Request.HttpMethod, 
                "GET", 
                StringComparison.OrdinalIgnoreCase);

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && isMethodGet)
            {
                throw new InvalidOperationException(
                    "GET not allowed! Change JsonRequestBehavior to AllowGet.");
            }

            var response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(this.ContentType) 
                ? "application/json" 
                : this.ContentType;

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (this.Data != null)
            {
                response.Write(JsonConvert.SerializeObject(this.Data));
            }
        }
    }
}

这可以应用于任何返回JsonResult以使用JSON的方法。网:

[JsonNetFilter]
public ActionResult GetJson()
{
    return Json(new { hello = new Date(2015, 03, 09) }, JsonRequestBehavior.AllowGet)
}

它会回应

{"hello":"2015-03-09T00:00:00+00:00"}

根据需要!


你可以,如果你不介意在每个请求时调用is比较,添加这个到你的FilterConfig:

// ...
filters.Add(new JsonNetFilterAttribute());

所有的JSON都将被JSON序列化。Net而不是内置的JavaScriptSerializer。

下面是我的Javascript解决方案——非常像JPot,但更短(可能更快一点):

value = new Date(parseInt(value.substr(6)));

"value.substr(6)"去掉"/Date("部分,parseInt函数忽略出现在结尾的非数字字符。

编辑:我故意省略了基数(parseInt的第二个参数);请看我下面的评论。另外,请注意ISO-8601日期比这种旧格式更受欢迎——因此这种格式通常不应该用于新的开发。

对于ISO-8601格式的JSON日期,只需将字符串传递给Date构造函数:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

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

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

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

我一直在研究这个问题的解决方案,因为上面的答案都没有真正帮助到我。我正在使用jquery周日历,需要我的日期在服务器和本地页面上有时区信息。经过一番深入研究,我想出了一个可能会帮助到其他人的解决方案。

我使用asp.net 3.5, vs 2008, asp.net MVC 2,和jquery周日历,

首先,我使用Steven Levithan编写的一个库,它有助于处理客户端上的日期,Steven Levithan的日期库。isoUtcDateTime格式非常适合我所需要的。在我的jquery AJAX调用中,我使用isoUtcDateTime格式库提供的格式函数,当AJAX调用命中我的动作方法时,datetime Kind被设置为本地并反映服务器时间。

当我通过AJAX发送日期到我的页面时,我通过使用“ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz”格式化日期将它们作为文本字符串发送。这种格式在客户端使用时很容易转换

var myDate = new Date(myReceivedDate);

以下是我的完整解决方案,减去Steve Levithan的源代码,你可以下载:

控制器:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }


    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}

Javascript:

<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

我希望这个简单的例子能帮助那些和我处境相同的人。在这个时候,它似乎工作得很好与微软JSON序列化和保持我的日期跨时区正确。