This is a nightmare (at least I can’t find an easy way), I have searched for hours and really can’t find my solution.
How do you handle dates in a custom format in web api? I need DD/MM/YYYY format
I can’t post my dates since my api wants them to be in the default format MM/DD/YY, one solution would be to parse all my dates via JavaScript to the format my api needs it, but for real? Isn’t it a cleaner way?
How can I make my api knows my format?
I found this post, and it says it does not work for posting. And no solution yet.
Am I in the wrong way? Too many up votes for the question, and not even a good answer!
-
Why not use a string and format it to whatever format you want? yourDate.ToString("dd/MM/yyyy") should do it.Gjohn– Gjohn2014年02月25日 02:53:34 +00:00Commented Feb 25, 2014 at 2:53
1 Answer 1
By default, as JSON formatter, in Web.Api, used Json.NET serializer. Json.NET writes dates in ISO 8601 format. Dates in UTC are written with a "Z" suffix. Dates in local time include a time-zone offset. For example:
2012年07月27日T18:51:45.53403Z // UTC
2012年07月27日T11:51:45.53403-07:00 // Local
You can override serrializer date time settings by setting the DateFormatString property in web api configuration section:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd";
}
}
Also, probably, you will need to change thread culture settings in Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
var newCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
newCulture.DateTimeFormat.ShortTimePattern = "HH:mm";
newCulture.DateTimeFormat.LongTimePattern = "HH:mm:ss";
newCulture.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = newCulture;
}