Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringify date in javascript in valid .Net format

I have a JSON object on client side that I want to get back on server side.
To do so, I have a hidden in which I put the stringified version of my object.

$("#<%=hidden.ClientID%>").val(JSON.stringify(obj));

Then, on server side, I try to deserialize it with JavaScriptSerializer.

My Problem : the stringified object contains a date and I can't parse it with de JavaScriptSerializer.
What I have done : Modify the date format to make it fit with the .Net format :

function FormatDate(date) {
    if (typeof (date.getTime) != "undefined") {
        return '\\/Date(' + date.getTime() + ')\\/'
    }

    return date;
}

Which seems to give a good format, but, when I use JSON.stringify on the object with the well formatted dates, it adds an extra backslash, so the JavaScriptSerializer still can't get it.

Any idea on how I could get it in a valid format in the hidden?

like image 463
Phil-R Avatar asked May 02 '26 11:05

Phil-R


1 Answers

I had the same Problem and

'\/Date(' + date.getTime() + ')\/';

works for me. You just have a double backslash instead of only one backslash.

like image 56
stefan.s Avatar answered May 05 '26 02:05

stefan.s