Learning Learning - 3 months ago 31
JSON Question

My custom date format is not formatting date with newton soft json in mvc

I am trying to display date in

dd-MM-yyyy
but the date i am getting is always in this format:


2016-08-08T16:17:40.643


I am using
asp.net mvc and returning data in json format
but displaying this date with angular js.

Here is the answer i am trying from the Link and i have combined the answer given by Perishable Dave and dav_i:

public class JsonNetFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is JsonResult == false)
{
return;
}

filterContext.Result = new JsonNetResult(
(JsonResult)filterContext.Result);
}

private class JsonNetResult : JsonResult
{
private const string _dateFormat = "dd-MM-yyyy";
public JsonNetResult(JsonResult jsonResult)
{

this.ContentEncoding = jsonResult.ContentEncoding;
this.ContentType = jsonResult.ContentType;
this.Data = jsonResult.Data;
this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
this.MaxJsonLength = jsonResult.MaxJsonLength;
this.RecursionLimit = jsonResult.RecursionLimit;
}

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

var isMethodGet = string.Equals(
context.HttpContext.Request.HttpMethod,
"GET",
StringComparison.OrdinalIgnoreCase);

if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& isMethodGet)
{
throw new InvalidOperationException(
"GET not allowed! Change JsonRequestBehavior to AllowGet.");
}

var response = context.HttpContext.Response;

response.ContentType = string.IsNullOrEmpty(this.ContentType)
? "application/json"
: this.ContentType;

if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}

if (this.Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(this.Data));
}
}
}
}

[JsonNetFilter]
public ActionResult GetJson()
{
return Json(new { hello = new Date(2016-08-02 05:49:11.000) }, JsonRequestBehavior.AllowGet)
}


How to date in
dd-MM-yyyy
format??

dbc dbc
Answer

You're not passing your isoConvert variable to JsonConvert.SerializeObject(this.Data), so it's never used. You need to pass it to SerializeObject using an appropriate overload:

response.Write(JsonConvert.SerializeObject(this.Data, new [] { isoConvert } ));
Comments