I have a following piece of JSON:
\/Date(1293034567877)\/
which is a result of this .NET code:
var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();
Now the problem I am facing is how to create a Date object from this in JavaScript. All I could find was incredible regex solution (many containing bugs).
It is hard to believe there is no elegant solution as this is all in JavaScrip, I mean JavaScript code trying to read JSON (JavaScript Object Notation) which is supposed to be a JavaScript code and at this moment it turns out it's not cause JavaScript cannot do a good job here.
I've also seen some eval solutions which I could not make to work (besides being pointed out as security threat).
Is there really no way to do it in an elegant way?
Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT
There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a
DateTime
at all; just send an RFC 1123 date stringToString("r")
or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct aDate
.The answer to this question is, use nuget to obtain JSON.NET then use this inside your
JsonResult
method:inside your view simple do this in
javascript
:If it is an ajax call:
Once
JSON.parse
has been called, you can put the JSON date into anew Date
instance becauseJsonConvert
creates a proper ISO time instanceusing eval function works just have to remove the forward slash at front and back.
yields Thu Jan 01 1970 00:00:00 GMT-0700 (US Mountain Standard Time)
I ran into an issue with external API providing dates in this format, some times even with UTC difference info like
/Date(123232313131+1000)/
. I was able to turn it jsDate
object with following codeThis answer from Roy Tinker here:
As he says: The substr function takes out the "/Date(" part, and the parseInt function gets the integer and ignores the ")/" at the end. The resulting number is passed into the Date constructor.
Another option is to simply format your information properly on the ASP side such that JavaScript can easily read it. Consider doing this for your dates:
Which should return a format like this:
If you pass this into a JavaScript
Date
constructor like this:The variable
date
now holds this value:Naturally, you can format this
DateTime
object into whatever sort of string/int the JSDate
constructor accepts.