I am using the OData and Web API 5.0, when I serialize the result from Queryable, the DateTime field always missing timezone, it is displayed like:

StartTime: "2013-08-12T10:00:00"

I have discover Microsoft OData implementation a bit, it seems OData use its own message writer to do serialize so I can not config the serializer to generate correct datetime string with timezone.

Does anybody know how to resolve this issue?

有帮助吗?

解决方案 2

The type "System.DateTime" does not include timezone information, to get the timezone you need to use "System.DateTimeOffset".

for example:

    var dateTime = new DateTime(...);
    var dtOffset = new DateTimeOffset(dateTime, new TimeSpan());
    var dtOffset2 = new DateTimeOffset(dateTime, new TimeSpan(1,0,0));

    //Assuming your pc is in the timezone GMT (+00:00)
    // if you .ToString() each of the above you should get something like this ...
    dateTime: "2013-08-12T10:00:00"
    dtOffset: "2013-08-12T10:00:00+00:00"
   dtOffset2: "2013-08-12T10:00:00+01:00"

If you change the timezone of you pc in windows then the change will be applied to the "dateTime" variable above and by default the variable "dtOffset" will use the timezone specified by windows, but in the "dtOffset2" variable i specified the timezone so that would always be fixed to +01:00.

OASIS have removed DateTime from the OData standard but I believe that Microsoft have kept it in their OData implementation, however their implementation assumes the Offset to be the machine offset.

其他提示

If you dont have sql 2008 or higher, you can also set the datatype in nhibernate to utcdatetime. Then it just assumes the datetime is utc, which is the only valid way of storing datetimes anyway

After some investigation, I found the problem was not caused by OData.

The problem was caused by the DateTime property read by NHibernate from the SQLSERVER database did not contain TimeZone infor, so without this information OData can only generate the date string without TimeZone.

Please refer to this link : It gives a very detail explain about NHibernate datetime problem

So my solution to this issue is switching from DateTime to DateTimeOffset type both in .NET code and SQLSERVER 2008. Then in database the DateTimeOffset column keep the TimeZone infor and when read by NHiberate it will pass the TimeZone information to .NET DateTimeOffset property.

DateTimeOffset was supported from SQLSERVER 2008.

If you're in doubt about the exact data type returned in your odata interface, inspect the meta data in the url: http://odata.domain.org/.svc/$metadata.

You will see Type Edm.DateTime for a local time field and Edm.DataTimeOffset for a UTC field. Only UTC will display time zone information.

See also OData documentation; 6. Primitive Data Types

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top