MS JSON date serialization and daylight saving time

牧云@^-^@ 提交于 2019-12-04 12:58:35

After much debugging I found the problem: I was ignorant of the way the JSON serializer works regarding the System.DateTime kind and the Date literal when (de)serializing dates back and forth between the server and the browser.

In detail, here's what happens. Suppose a service has to return a DateTime value to a client in JSON format. The DataContractJsonSerializer will produce a string in the (infamous) /Date(UTC ticks)/ format, which the client can parse into a JavaScript Date value. This serialization is sensitive to the DateTime's Kind property:

  • When the Kind is DateTimeKind.Utc, the string literal will contain "/Date(UTC ticks)/" and no time zone.
  • When the Kind is DateTimeKind.Local, the string literal will contain "/Date(UTC ticks-time zone)/".
  • If the Kind is DateTimeKind.Unspecified, it is assumed Local.

Conversely, if the client sends a date value to the service, the serialization process is also sensitive to the "kind" of the JSON literal:

  • When the literal is in the format "/Date(UTC ticks)/" with no time zone, the produced DateTime will be of DateTimeKind.Utc kind.
  • When the literal is in the format "/Date(UTC ticks-time zone)/", the produced DateTime will be of DateTimeKind.Local kind.

All I had to do is make sure the client sends only UTC-formatted Date literals to the service. All is great now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!