ASP.NET MVC JsonResult Date Format

前端 未结 25 3247
渐次进展
渐次进展 2020-11-21 11:22

I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:

return new JsonRes         


        
相关标签:
25条回答
  • I had the same problem and instead of returning the actual date value I just used ToString("dd MMM yyyy") on it. Then in my javascript I used new Date(datevalue), where datevalue may be "01 Jan 2009".

    0 讨论(0)
  • 2020-11-21 11:45

    Format the date within the query.

    var _myModel = from _m in model.ModelSearch(word)
        select new { date = ((DateTime)_m.Date).ToShortDateString() };
    

    The only problem with this solution is that you won't get any results if ANY of the date values are null. To get around this you could either put conditional statements in your query BEFORE you select the date that ignores date nulls or you could set up a query to get all the results and then loop through all of that info using a foreach loop and assign a value to all dates that are null BEFORE you do your SELECT new.

    Example of both:

    var _test = from _t in adc.ItemSearchTest(word)
                            where _t.Date != null
                            select new { date = ((DateTime)_t.Date).ToShortDateString() };
    

    The second option requires another query entirely so you can assign values to all nulls. This and the foreach loop would have to be BEFORE your query that selects the values.

    var _testA = from _t in adc.ItemSearchTest(word)
                             select _i;
    
                foreach (var detail in _testA)
                {
                    if (detail.Date== null)
                    {
                        detail.Date= Convert.ToDateTime("1/1/0001");
                    }
                }
    

    Just an idea which I found easier than all of the javascript examples.

    0 讨论(0)
  • 2020-11-21 11:47

    Not for nothing, but there is another way. First, construct your LINQ query. Then, construct a query of the Enumerated result and apply whatever type of formatting works for you.

    var query = from t in db.Table select new { t.DateField };
    var result = from c in query.AsEnumerable() select new { c.DateField.toString("dd MMM yyy") };
    

    I have to say, the extra step is annoying, but it works nicely.

    0 讨论(0)
  • 2020-11-21 11:47

    It returns Server Date Format. You need to define your own function.

    function jsonDateFormat(jsonDate) {
      // Changed data format;
      return (new Date(parseInt(jsonDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");
    };
    
    0 讨论(0)
  • 2020-11-21 11:49

    There are quite a bit of answers to handle it client side, but you can change the output server side if you desired.

    There are a few ways to approach this, I'll start with the basics. You'll have to subclass the JsonResult class and override the ExecuteResult method. From there you can take a few different approaches to change the serialization.

    Approach 1: The default implementation uses the JsonScriptSerializer. If you take a look at the documentation, you can use the RegisterConverters method to add custom JavaScriptConverters. There are a few problems with this though: The JavaScriptConverter serializes to a dictionary, that is it takes an object and serializes to a Json dictionary. In order to make the object serialize to a string it requires a bit of hackery, see post. This particular hack will also escape the string.

    public class CustomJsonResult : JsonResult
    {
        private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
    
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
    
            HttpResponseBase response = context.HttpContext.Response;
    
            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
    
                // Use your custom JavaScriptConverter subclass here.
                serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });
    
                response.Write(serializer.Serialize(Data));
            }
        }
    }
    

    Approach 2 (recommended): The second approach is to start with the overridden JsonResult and go with another Json serializer, in my case the Json.NET serializer. This doesn't require the hackery of approach 1. Here is my implementation of the JsonResult subclass:

    public class CustomJsonResult : JsonResult
    {
        private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
    
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
    
            HttpResponseBase response = context.HttpContext.Response;
    
            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                // Using Json.NET serializer
                var isoConvert = new IsoDateTimeConverter();
                isoConvert.DateTimeFormat = _dateFormat;
                response.Write(JsonConvert.SerializeObject(Data, isoConvert));
            }
        }
    }
    

    Usage Example:

    [HttpGet]
    public ActionResult Index() {
        return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
    }
    

    Additional credits: James Newton-King

    0 讨论(0)
  • 2020-11-21 11:50

    Here's my solution in Javascript - very much like JPot's, but shorter (and possibly a tiny bit faster):

    value = new Date(parseInt(value.substr(6)));
    

    "value.substr(6)" takes out the "/Date(" part, and the parseInt function ignores the non-number characters that occur at the end.

    EDIT: I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below. Also, please note that ISO-8601 dates are preferred over this old format -- so this format generally shouldn't be used for new development. See the excellent Json.NET library for a great alternative that serializes dates using the ISO-8601 format.

    For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

    var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
    
    0 讨论(0)
提交回复
热议问题