问题
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