我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:
return new JsonResult(myModel);
这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:
"\/Date(1239018869048)\/"
我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?
我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:
return new JsonResult(myModel);
这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:
"\/Date(1239018869048)\/"
我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?
当前回答
这里是我写的一些JavaScript代码,它设置了一个<input type="date">值,从一个从ASP传递的日期。净MVC。
var setDate = function(id, d) {
if (d !== undefined && d !== null) {
var date = new Date(parseInt(d.replace("/Date(", "").replace(")/", ""), 10));
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var parsedDate = date.getFullYear() + "-" + (month) + "-" + (day);
$(id).val(parsedDate);
}
};
你可以这样调用这个函数:
setDate('#productCommissionStartDate', data.commissionStartDate);
其中commissionStartDate是MVC传递的JSON日期。
其他回答
让我们扩展一下casperOne的答案。
JSON规范没有说明Date值。MS不得不进行调用,他们选择的路径是利用javascript字符串表示中的一个小技巧:字符串字面量“/”与“\/”相同,字符串字面量永远不会被序列化为“\/”(甚至“\/”也必须映射为“\\/”)。
参见http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2获得更好的解释(向下滚动到“从JavaScript文字到JSON”)
One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".
一个解决办法就是把它解析出来:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
然而,我听说在某个地方有一个设置,可以让序列化器用新的Date(xxx)语法输出DateTime对象。我试着把它挖出来。
JSON.parse()的第二个参数接受一个恢复函数,其中规定了在返回值之前最初是如何生成值的。
下面是一个关于date的例子:
var parsed = JSON.parse(data, function(key, value) {
if (typeof value === 'string') {
var d = /\/Date\((\d*)\)\//.exec(value);
return (d) ? new Date(+d[1]) : value;
}
return value;
});
查看JSON.parse()的文档
在查询中格式化日期。
var _myModel = from _m in model.ModelSearch(word)
select new { date = ((DateTime)_m.Date).ToShortDateString() };
此解决方案的唯一问题是,如果任何日期值为空,则不会得到任何结果。为了解决这个问题,你可以在你选择忽略日期null的日期之前在你的查询中放入条件语句,或者你可以设置一个查询来获得所有结果,然后使用foreach循环遍历所有这些信息,并在你执行select new之前为所有日期赋值。
两者的例子:
var _test = from _t in adc.ItemSearchTest(word)
where _t.Date != null
select new { date = ((DateTime)_t.Date).ToShortDateString() };
第二个选项需要完全另一个查询,因此可以将值赋给所有空值。这个循环和foreach循环必须在选择值的查询之前。
var _testA = from _t in adc.ItemSearchTest(word)
select _i;
foreach (var detail in _testA)
{
if (detail.Date== null)
{
detail.Date= Convert.ToDateTime("1/1/0001");
}
}
只是一个想法,我发现比所有的javascript例子更容易。
重写控制器Json/JsonResult以返回Json。Net:
这很有用
在knockoutjs中处理日期的更好方法是使用moment库并像boss一样处理日期。您可以轻松地处理/Date(-62135578800000)/这样的日期。不需要担心如何在控制器中序列化日期。
function jsonToDate(date,format) {
return moment(date).format(format);
}
像这样使用它
var formattedDate = jsonToDate(date,'MM/DD/YYYY')
Momentjs支持大量的日期时间格式和日期实用函数。
它返回服务器日期格式。你需要定义自己的函数。
function jsonDateFormat(jsonDate) {
// Changed data format;
return (new Date(parseInt(jsonDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");
};