Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JavascriptSerializer serialized DateTime string to Javascript Date object

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?

like image 988
dragonfly Avatar asked Apr 23 '13 08:04

dragonfly


2 Answers

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)/");
like image 198
Jefferey Cave Avatar answered Nov 18 '22 23:11

Jefferey Cave


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");
like image 12
Hakan KOSE Avatar answered Nov 18 '22 23:11

Hakan KOSE