2

I'm sending via SignalR a DateTime Object from ServerSide without unspecified kind:

myDate.Kind //Unspecified

I'm setting the JsonConvert defaultSettings to use UTC, as suggested here:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings(){
      DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

If I use the JsonConvert.SerializeObject I obtain the string in UTC ISO8601 format, with "Z" suffix:

JsonConvert.SerializeObject(myDate) // "\"2014-11-27T23:00:00Z\""

But, If I send the object via SignalR, at client side I Receive:

myDate: "2014-11-27T23:00:00" 

Notice it returns without Z suffix.

Is SignalR not using JsonConvert? Why I'm getting two different results?

My goal is to receive client side: "2014-11-27T23:00:00Z"

Community
  • 1
  • 1
Mario Levrero
  • 3,345
  • 4
  • 26
  • 57

2 Answers2

6

SignalR uses a registered JsonSerializer from the GlobalHost object. Instead of what you are doing, add the following;

 var serializer = new JsonSerializer()
 {
     DateTimeZoneHandling = DateTimeZoneHandling.Utc
 };
 GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

Don't forget that (if needed) to set your Null handling, Reference handling, etc.

2

Updating this answer for SignalR 2.2.0 and giving a little bit of info where to put the code, I put this code in Global.asax.cs:

{ ... other using ... }
using Newtonsoft.Json;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Json;

public class MvcApplication : System.Web.HttpApplication
{

    protected void Application_Start()
    {
        { ... other code ... }

        /* Need to using UTC time for SignalR so IE and Chrome display dates correctly 
         * (append Z (Zulu) onto end of json timestamps) */
        var settings = JsonUtility.CreateDefaultSerializerSettings();
        settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
        var serializer = JsonSerializer.Create(settings);
        GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
    }

    { .. more code .. }
}

This is required so SignalR includes a "Z" (Zulu) on the end of datetime json values. Chrome (v44.x) handles the datetimes without Z as UTC but IE11 treats datetimes as local instead of UTC. Adding Z to end of datetime json values makes the handling consistent in my experience.

Paul Cooper
  • 196
  • 2
  • 7