如何使用JSON.NET通过ASP.NET MVC传递JSON日期值?

Chr*_*isP 36 javascript asp.net-mvc datetime json json.net

可能重复:
格式化Microsoft JSON日期?

ASP.NET函数Json()格式化并返回日期为

{"d":"\/Date(1240718400000)\/"}
Run Code Online (Sandbox Code Playgroud)

必须在客户端处理这是有问题的.您对来回发送日期值的方法有何建议?

Jim*_*mbo 29

这是在Stack Overflow上的另一篇文章中找到的:

var date = new Date(parseInt(jsonDate.substr(6))); 
Run Code Online (Sandbox Code Playgroud)

The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.


Rya*_*lor 11

如果您没有绑定到MS JSON序列化程序,则可以使用Json.NET.它附带了一个IsoDateTimeConverter来处理序列化日期的问题.这会将日期序列化为ISO 8601格式的字符串.

例如,在我们的项目中,序列化myObject通过以下代码处理.

JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
jsonNetResult.Data = myObject;
Run Code Online (Sandbox Code Playgroud)

如果你决定采用Json.NET 插件,你也会想要抓住JsonNetResult,因为它返回一个可以在ASP.NET MVC应用程序中使用的ActionResult.它很容易使用.

有关更多信息,请参阅:Json.NET的好(日期)时间


Fel*_*lix 6

它可能很丑,但它有效:

 var epoch = (new RegExp('/Date\\((-?[0-9]+)\\)/')).exec(d);
 $("#field").text((new Date(parseInt(epoch[1]))).toDateString());
Run Code Online (Sandbox Code Playgroud)

可能没有必要匹配整个字符串,只是( - ?[0-9] +)就够了......


Dav*_*ard 5

不是每个人都同意我这是一个好主意,但我发现自己经常返回格式化的字符串而不是正确的日期.请参阅如何处理ASP.NET AJAX返回的JSON日期.


Ale*_*lex 0

查看博客文章jQuery、Ajax、ASP.NET 和日期

它详细介绍了如何使用 ASP.NET MVC 和 jQuery 在服务器和客户端之间通过 JSON 传递日期。