如何处理从 WCF 数据服务 (OData) 返回的 json DateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3818719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle json DateTime returned from WCF Data Services (OData)
提问by Andy May
I believe I am missing something obvious here. When I request a JSON response from an OData service I get a different result for the DateTime properties than I do when I request XML. I'll use the NerdDinner OData feed as an example.
我相信我在这里遗漏了一些明显的东西。当我从 OData 服务请求 JSON 响应时,我得到的 DateTime 属性结果与我请求 XML 时得到的结果不同。我将使用 NerdDinner OData 提要作为示例。
JSON:
JSON:
http://www.nerddinner.com/Services/OData.svc/Dinners(1)?$format=json
"EventDate": "\/Date(1235764800000)\/"
XML:
XML:
http://www.nerddinner.com/Services/OData.svc/Dinners(1)
<d:EventDate m:type="Edm.DateTime">2009-02-27T20:00:00</d:EventDate>
When I do an alert(new Date(1235764800000)) I get this result:

当我做一个 alert(new Date(1235764800000)) 我得到这个结果:

I also get a result of 8PM when I run the same query with LINQPad. Why is the time zone incorrect in the JSON result?It seems to assume that the response is in GMT. Should I handle this on the client (via javascript) or is this something that I can set on the server?
当我使用 LINQPad 运行相同的查询时,我也得到了 8PM 的结果。为什么 JSON 结果中的时区不正确?似乎假设响应是格林威治标准时间。我应该在客户端处理这个(通过javascript)还是我可以在服务器上设置?
I'm using jQuery on the client and WCF Data Services (and Entity Framework) on the server.
我在客户端使用 jQuery,在服务器上使用 WCF 数据服务(和实体框架)。
Update:
更新:
I am using Datejson the client side to handle the UTC datetime formatting. I'm wondering if this is the correct way to go about this problem.
我在客户端使用Datejs来处理 UTC 日期时间格式。我想知道这是否是解决这个问题的正确方法。
function getDateString(jsonDate) {
if (jsonDate == undefined) {
return "";
}
var utcTime = parseInt(jsonDate.substr(6));
var date = new Date(utcTime);
var minutesOffset = date.getTimezoneOffset();
return date.addMinutes(minutesOffset).toString("M/d/yyyy h:mm tt");
}
采纳答案by Bryan
According to this msdn link, DateTimeobjects are...
根据此 msdn 链接,DateTime对象是...
...represented in JSON as "/Date(number of ticks)/". The number of ticks is a positive or negative long value that indicates the number of ticks (milliseconds) that have elapsed since midnight 01 January, 1970 UTC.
...在 JSON 中表示为“/Date(number of ticks)/”。刻度数是一个正或负的 long 值,表示自 1970 年 1 月 1 日午夜 UTC 以来经过的刻度数(毫秒)。
So you are correct that .NET assumes, but it's UTC instead of GMT (though they are similar). There are somegoodanswershere on SO that give more details and also provide methods for parsing the JSON into a usable date on the client.
所以 .NET 假设是正确的,但它是 UTC 而不是 GMT(尽管它们很相似)。SO 上有一些很好的答案,它们提供了更多详细信息,还提供了将 JSON 解析为客户端可用日期的方法。
As far as converting dates from UTC to a specific time zone, on the server you could use the TimeZoneInfoclass which has a ConvertTimeFromUtcmethod. Or you could write a custom converter that inherits from the JavaScriptConverterclass. In javascript, there are the UTCand getTimezoneOffsetmethods that could be used.
至于将日期从 UTC 转换为特定时区,在服务器上您可以使用TimeZoneInfo具有ConvertTimeFromUtc方法的类。或者您可以编写一个从JavaScriptConverter类继承的自定义转换器。在 javascript 中,可以使用UTC和getTimezoneOffset方法。
Hope this helps and good luck.
希望这会有所帮助并祝你好运。
回答by Andrea Celin
If this may help, I was facing the same problem and I ended to implement something like this, not so elegant but it works.
如果这可能有帮助,我遇到了同样的问题,我最终实现了这样的东西,不是那么优雅,但它有效。
String.prototype.DateWCF = function(dateformat) {
return new Date(parseInt(this.match(/\/Date\(([0-9]+)(?:.*)\)\//)[1])).format(dateformat);
};
then on $.ajaxsuccess:
然后$.ajax成功:
success: function(data) {
$.each(data, function() {
var hello = this.DateTimeProperty.DateWCF('dd-MM-yyyy'));
});
}
I hope this may be helpful.
我希望这可能会有所帮助。
回答by d1jhoni1b
This should work just fine:
这应该可以正常工作:
var date = new Date(parseInt(jsonDate.substr(6)));
The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end.
substr 函数取出“/Date(”部分,parseInt 函数获取整数并忽略末尾的“)/”。
For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:
对于 ISO-8601 格式的 JSON 日期,只需将字符串传递给 Date 构造函数:
var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
This was already fixed and discussed that a look at this previous post
这已经得到修复和讨论,看看这个以前的帖子
回答by Mshini
Using date.js script.Try below
使用 date.js 脚本。试试下面
new Date(parseInt(yourDateValue)).toString("ddd, dd-MMM-yyyy, hh:mm:ss")
回答by Alex Ross
If you're parsing WCF JSON date responses in Javascript, the Moment.js date framework removes much of the headache: Moment.js - Parsing ASP.NET JSON Dates. It also has some other handy methods.
如果您在 Javascript 中解析 WCF JSON 日期响应,Moment.js 日期框架消除了很多令人头疼的问题:Moment.js - 解析 ASP.NET JSON 日期。它还有一些其他方便的方法。
回答by Anton Sivov
Try this:
尝试这个:
function getDate(datestr) {
return new Date(eval('new ' + datestr.replace(/\//g, '')));
}
回答by Mike Gledhill
This reply might get voted down (!!) but an alternative solution is to just change your WCF Service to return the dates in a more friendly way.
此回复可能会被否决 (!!) 但另一种解决方案是更改您的 WCF 服务以更友好的方式返回日期。
Here's some sample JSON from my WCF service, showing a UpdateDateOriginalvalue (using the annoying default formatting that WCF has used for my DateTime value), and a friendlier UpdateDateversion of the same DateTime value.
这是来自我的 WCF 服务的一些示例 JSON,显示了一个UpdateDateOriginal值(使用 WCF 用于我的 DateTime 值的烦人的默认格式),以及UpdateDate相同 DateTime 值的更友好版本。


I've posted the code to do this in the following article:
我已在以下文章中发布了执行此操作的代码:
回答by Mark Stafford - MSFT
We produce data.jsas a JavaScript client for OData services. If you're working from a Web client, using this library will remove this headache as well as prevent you from running into others.
我们生产data.js作为 OData 服务的 JavaScript 客户端。如果您使用 Web 客户端工作,使用这个库将消除这个头痛并防止您遇到其他人。
Data.js handles all of the JSONP and other concerns on your behalf, making requesting and parsing JSON data this easy:
Data.js 代表您处理所有 JSONP 和其他问题,使请求和解析 JSON 数据变得如此简单:
OData.read(
"http://services.odata.org/Northwind/Northwind.svc/Categories",
function (data) {
var html = "";
$.each(data.results, function(l) { html += "<div>" + l.CategoryName + "</div>"; });
$(html).appendTo($("#target-element-id"));
}
);

