Search code examples
javascriptasp.netdatetimeutc

Chrome interprets ISO time without Z as UTC; C# issue


Run this jsfiddle: http://jsfiddle.net/E9gq9/7/ on Chrome, FF, and IE and you get:

Chrome:

Chrome http://images.devs-on.net/Image/vBTz86J0f4o8zlL3-Region.png

Firefox:

Firefox http://images.devs-on.net/Image/aNPxNPUpltyjVpSX-Region.png

IE:

IE http://images.devs-on.net/Image/WXLM5Ev1Viq4ecFq-Region.png

Safari:

Safari http://images.devs-on.net/Image/AEcyUouX04k2yIPo-Region.png

ISO 8601 does not appear to say how a string without a trailing Z should be interpreted.

Our server (ASP.NET MVC4) is pulling UTC times out of our database as DateTimes and simply stuffing them in JSON. As you can see because of this we are getting inconsistent results on the browser.

Should we just append Z to them on the server side?


Solution

  • At the end of the day, the problem I'm facing in this app can be fixed if my server always sends the client DateTime objects in a format that all browsers deal with correctly.

    This means there must be that 'Z' on the end. Turns out the ASP.NET MVC4 Json serializer is based on Json.NET, but does not have Utc turned on by default. The default for DateTimeZoneHandling appears to be RoundtripKind and this does not output the values with Z on them, even if DateTime.Kind == Utc, which is quite annoying.

    So the fix appears to be, set the way Json.NET handles timezones to DateTimeZoneHandling.Utc:

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    // Force Utc formatting ('Z' at end). 
    json.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
    

    Now, everything coming down the wire from my server to the browser is formatted as ISO-8601 with a 'Z' at the end. And all browsers I've tested with do the right thing with this.