I am returning a DateTime as JsonResult. However, I am having a value as follows:
"/Date(1303070400000)/"
How Can I set the JSon value in a Date format in Javascript?
I am returning a DateTime as JsonResult. However, I am having a value as follows:
"/Date(1303070400000)/"
How Can I set the JSon value in a Date format in Javascript?
I've written a custom jQuery extension that auto-converts .Net as well as ISO dates to actual Javascript dates.
It actually extends existing $.parseJSON()
function which can now take additional parameter:
$.parseJSON([String] json, [optional Boolean] convertDates);
So whenever you want your dates to be auto converted, just set last parameter to true
. The good thing is it won't interfere with your existing code, since last parameter is optional and when not provided it works the same as original function works. It only converts dates when you instruct it so.
I'm personally using a slightly modified version of the same extension which works the other way around. It always converts dates unless I instruct it not to, so I always get dates even when internal jQuery functionality calls .parseJSON
function (ie. when calling $.ajax
with type JSON etc). If you need it to work the same, either let me know or change extension code at your will. It's rather easy to find its way around it.
This is by far the most transparent jQuery date conversion.
you can try this
new Date(parseInt("/Date(1303070400000)/".replace("/Date(", "").replace(")/", ""), 10))
I use the folluwing function for this purpose
function ConvertJsonDate(jsondate) {
if (!jsondate)
return "";
var dt = new Date(+(jsondate).substr(6, 13));
var m = dt.getMonth() + 1;
var d = dt.getDate();
if (m < 10)
m = "0" + m;
if (d < 10)
d = "0" + d;
return d + "-" + m + "-" + dt.getFullYear();
}
I simply use the following:
var dateString = "/Date(1303070400000)/";
var dt = new Date(parseInt(dateString.substr(6)));
The json2.js library, http://json.org and the jQuery JSON parser should just naturally turn this into a Date value for you when the JSON is deserialized.