How to handle json DateTime returned from WCF Data

2019-01-09 00:47发布

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.

JSON:

http://www.nerddinner.com/Services/OData.svc/Dinners(1)?$format=json
"EventDate": "\/Date(1235764800000)\/"

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: alt text

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?

I'm using jQuery on the client and WCF Data Services (and Entity Framework) on the server.

Update:

I am using Datejs on the client side to handle the UTC datetime formatting. I'm wondering if this is the correct way to go about this problem.

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

8条回答
放荡不羁爱自由
2楼-- · 2019-01-09 01:47

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.

Here's some sample JSON from my WCF service, showing a UpdateDateOriginal value (using the annoying default formatting that WCF has used for my DateTime value), and a friendlier UpdateDate version of the same DateTime value.

enter image description here

I've posted the code to do this in the following article:

Change default date serialization in WCF

查看更多
甜甜的少女心
3楼-- · 2019-01-09 01:51

According to this msdn link, DateTime objects are...

...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.

So you are correct that .NET assumes, but it's UTC instead of GMT (though they are similar). There are some good answers here on SO that give more details and also provide methods for parsing the JSON into a usable date on the client.

As far as converting dates from UTC to a specific time zone, on the server you could use the TimeZoneInfo class which has a ConvertTimeFromUtc method. Or you could write a custom converter that inherits from the JavaScriptConverter class. In javascript, there are the UTC and getTimezoneOffset methods that could be used.

Hope this helps and good luck.

查看更多
登录 后发表回答