Search code examples
jsondatetimeodatadatacontractserializer

ASP.NET 4.5 OData serialize DateTime to Json missing timezone


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?


Solution

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