After serializing an object with DateTime
field with JavaScriptSerializer
, I see that the DateTime
field looks like this:
EffectiveFrom: "/Date(1355496152000)/"
How can I convert this string to Javascript Date object?
UPDATE: This answer may not be appropriate in all cases. See JD's answer for an elegant solution that is likely better.
You could just "fix" the output from JavaScriptSerializer
on the .Net side of things:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(this);
json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","new Date($1)");
return json;
This would change
EffectiveFrom: "/Date(1355496152000)/"
to
EffectiveFrom: new Date(1355496152000)
Which is directly consumable by Javascript
EDIT: update to accommodate negative dates
EDIT: Here is the Regex line for VB folks:
json = Regex.Replace(json, """\\/Date\((-?\d+)\)\\/""", "new Date($1)")
UPDATE 2016.11.20: With a lot more datetime handling in javascript/json behind me, I would suggest changing the regex to something as simple as
json = Regex.Replace(json,@"\""\\/Date\((-?\d+)\)\\/\""","$1");
The resulting value is valid JSON, and can be converted to a Date object on the javascript side.
It is also worth noting that moment.js (http://momentjs.com/docs/#/parsing/) handles this format happily enough.
moment("/Date(1198908717056-0700)/");
There is an answer that may help you:
Parsing Date-and-Times from JavaScript to C#
If you want to parse datetime string to datetime value with javascript you must use "new Date" like this:
var data = new Date("1355496152000");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With