2

I need every DateTime object to be in the basic format of "yyyy-MM-dd".

When I was using JSON.Net to do this, it worked fine by adding the following to the WebApiConfig.cs:

    config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
        new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" });

However, I have reworked my controllers to return IHttpActionResult and just return Json(objectToSerialize). Now the date formats are wrong as I assume that's because this is now using the JavaScriptConverter. Let me know if I'm wrong.

How do I convert every DateTime in my serialized object into the format I need?

By default, they are now showing as "1927-01-29T00:00:00" ... I need "1927-01-29".

I've seen some crazy hacks that seem like total overkill (such as this one).

Is there a clean way to do this?

2
  • But do you really need use JavaScriptConverter? Commented Mar 27, 2016 at 22:20
  • Honestly I have no idea, which is why I'm asking. I would prefer a global configuration setting that forces Web API to format ALL dates in this format when serializing objects. The controller returns IHttpActionResult and the return line is return Json(myObject). Commented Mar 27, 2016 at 22:21

1 Answer 1

3

Well, you can still use IHttpActionResult but what you return is not the correct thing. In your case I believe you can fix it via:

return Ok(objectToSerialize);

it will keep JSON.NET by default in WebApi and you should have your date formatting kept

Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick. Thanks. I have to rewrite a lot of my unit tests that expected JsonResult and are now seeing OkNegotiatedContentResult but that's fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.