Weird Date Format Help
I created an extension method that uses the built-in ASP.NET serializer to serialize my 开发者_C百科objects into JSON to send back to my server via AJAX like so:
namespace ExtensionMethods.Json
{
public static class JsonHelper
{
public static string ToJson(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJson(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
//usage
String json = myObject.ToJson();
This works fine, except for dates, as it sends back dates in this format:
/Date(1291276800000)/
Is there a way to fix this serverside so that the date comes into something more manageable, or will have to do some stupid character parsing on the client side (ie, scrape the digits out of the parens and try to set a date using that number as milliseconds)? Or is there a better way I'm simply overlooking? I've tried Date.parse([the date])
but it errors out with "Invalid date format".
That is a valid Json Date. Have a look at this other SO question to help you get that date back. How do I format a Microsoft JSON date?
I used JavaScript Date Format date format extension of the Date type. It has worked well with the JSON formatted dates.
I include the .js file and get my dates formatted like this:
function formatJsonDate(jsonDate, formatString) {
var dt = new Date(+jsonDate.replace(/\/Date\((\d+)\)\//, '$1'));
return dt.format(formatString);
}
var formattedDate = formatJsonDate(jsonDate, "mm/dd/yyyy");
There are even some predefined date format masks such as :
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
I had this problem too and decided to just move all of my date objects over to Unix timestamps and parse them back. It's extra work, but it keeps the funny formatting out. If you have a class variable of the long
datatype it should hold a timestamp pretty nicely.
There's some pretty solid samples over here.
http://www.epochconverter.com/
For the answer to this, this is basically what I used:
function parseJsonDate (date, shortFormat) {
if (date != null) {
var d = new Date(parseInt(date.substr(6)));
if (shortFormat) {
return (d.getMonth() + 1) + '/' + d.getDate() + '/' +
d.getFullYear().toString().substr(2);
}
return d;
} else {
return null;
}
}
精彩评论