SignalR datetime format

拥有回忆 提交于 2019-12-24 02:39:15

问题


I'm using SignalR in my server side code c# .net4. On client I'm using javascript.

when I Invoke client method from server ,for example

    Caller.ShowDate(DateTime.Now);

client side javascript gets value of "2012-11-13T19:02:39.3386544+02:00" as string.

How can I use It as Date in javascript ?


回答1:


Keep in mind that client times can be VASTLY different than server times due to time zones/clients modifying clocks etc. That being said:

C#:

Caller.ShowDate(DateTime.UtcNow);

JavaScript:

myHub.client.ShowDate = function(d) {
    var serverTime = new Date(d); // The Server Time in JavaScript
}



回答2:


If you unhappy man which use IE8 then can read comment below:

SignalR uses Json.Net-library to (de)serialize data.

Before .NET 4.5 Json.NET used epoch-format ("/Date(1198908717056)/") and then began to be used ISO8601 standard ("2012-03-19T07:22Z") [see Serializing Dates in JSON].

If you want to use epoch-format you need to reconfigure json-serializator [see Replacing the IJsonSerializer]:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        var serializer = new JsonNetSerializer(new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
            NullValueHandling = NullValueHandling.Ignore
        });

        GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer); 
    }
}

On client side you can use this code to convert epoch-time to Date:

function epochUtcToDate(epochUtc) {
    return new Date(parseInt(epochUtc.substr(6), 10));
};



回答3:


If you have add time zone to Json date you need use local time from server

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        GlobalHost.HubPipeline.AddModule(new ElmahPipelineModule());
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {
            };
            map.RunSignalR(hubConfiguration);
        });
        var jsonSerializer =  new JsonSerializer();
        jsonSerializer.DateFormatHandling = DateFormatHandling.IsoDateFormat;
        jsonSerializer.DateTimeZoneHandling = DateTimeZoneHandling.Local;
        jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
        GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => jsonSerializer);


    }
}


来源:https://stackoverflow.com/questions/13365294/signalr-datetime-format

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