I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as:
/Date(1237588418563+0000)/
When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it.
Any ideas what I can do with this?
The JSON object contained something like this:
but, still it would be better to fix the JSON object so the date function fired without using something like eval() or window[]. Maybe in jQuery. Not sure.
Don't forget that the offset could be
+
and not just-
for the offset!Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date.
Documentation: Serializing Dates in JSON with Json.NET
As of Newtonsoft Json.Net version 4.5r5 you use the JsonPropertyAttribute Class class and set its ItemConverterType Property property. Usage:
As I have observed this will set the DateTimeConverter for all properties in this class not just the one before which is declared.
This works for me
I came up with a different approach which might be useful to some. Basically I create my own CustomDateConverter that I call when I need it. The converter takes 2 parameters, a date format e.g.
yyyy-MM-dd HH:mm:ss
and a TimeZoneInfo, which allows me to convert the date from UTC to the user's time zone:You can use it like this:
Obviously you could remove anything related to time zone if you only want custom date formatting. Let me know it that helped!
Ran into the same problem, and found a solution based on the link from Adam:
It looks like a Unix timestamp, which javascript is easily able to convert into a date object. The
- 0
is simply to make javascript treat thesubstr
output as an integer... I guess you couldNumber()
it as well, if you don't like the looks of- 0