Parsing DateTime serialized from signalR
-
12-11-2019 - |
Вопрос
Using the very nice signalR library, I have a broadcast message that sends an object of type ChangeDetail
to the client browsers. The object sent includes a DateTime property:
var change = new ChangeDetail();
change.TimeOfChange = DateTime.Now();
When I send this to the clients, SignalR takes care of the serializing of the objects to JSON, but in the client javascript code when I inspect the object, it looks like this:
console.log (change.TimeOfChange); --> "/Date(1327332563969)/"
How I get that back into a js Date object? I could write a regex to get the number, and the Date.parse with that number, but that seems a little cumbersome...?
Решение
I have typically added the following prototype extension to String.
String.prototype.toDate = function () {
"use strict";
var match = /\/Date\((\d{13})\)\//.exec(this);
return match === null ? null : new Date(parseInt(match[1], 10));
};
Basically you can go change.TimeOfChange.toDate()
to get back an actual date object
Не связан с StackOverflow