开发者

WCF REST JSON API: DateTime serialization in DataContractJsonSerializer

开发者 https://www.devze.com 2023-02-26 17:25 出处:网络
does anyone know why DataContractJsonSerializer serializes DateTime properties to include the timezone?i.e., 开发者_如何学PythonI have a .NET DateTime on an object which is being serialized to JSON.It

does anyone know why DataContractJsonSerializer serializes DateTime properties to include the timezone? i.e., 开发者_如何学PythonI have a .NET DateTime on an object which is being serialized to JSON. It's serializing to 1303500600000+0000 instead of 1303500600000.

This means that when it's deserialized by DataContractJsonSerializer inside a client app, it will be converted to the "local" time. In reality, the datetime should remain timezone agnostic.


I ran into this exact same issue. Was developing everything local PST and pushed to a server EST which then obviously caused some fun issues. I was never able to find a good explanation why this is, but it is related to the DateTime.Kind. By default DateTimeKind on a DateTime is Unspecified, which the Serializer converts to "Local", thus adding the timezone offset.

The way I ended up working around this is by setting the DateTime.Kind to UTC:

http://msdn.microsoft.com/en-us/library/shx7s921.aspx

Here's another forum answer to the question:

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0a6c84a3-5348-4ea0-b33f-eb411a2e1c97

If the DateTime.Kind is Utc the serializer excludes the TimeZone offset and you can track all that yourself and make whatever assumptions you need to on both the server and client about the TimeZone of your dates.


try this

yourDate.ToUniversalTime()

source : here

0

精彩评论

暂无评论...
验证码 换一张
取 消