0

How can I control DateTime output format when content is requested as application/xml? The following works for JSON:

 JsonMediaTypeFormatter jsonFormatter = config.Formatters.JsonFormatter;
 jsonFormatter.SerializerSettings = new JsonSerializerSettings {
     DateFormatString = "yyyy-MM-dd" };

What's the equivalent for XmlMediaTypeFormatter ?

Update: Semantically, my data have no time information. Technically, I want to a) minimize payload b) simplify consumption (no need to process/format on client side) c) consistent responses regardless of format asked.

UserControl
  • 14,766
  • 20
  • 100
  • 187
  • What are you trying to change it to, and why? XML already has a well-defined format for dates and times (ISO-8601) - you should stick with that. Don't forget this is meant to be *machine-readable*, not aimed at end users. (Likewise the JSON - I'd strongly discourage the use of `MM/dd/yyyy` in JSON.) – Jon Skeet Nov 14 '14 at 10:57
  • Unfortunately the underlaying DB stores dates using datetime datatype. C# does not have date only type as well, right? And my front-end needs date parts only. – UserControl Nov 14 '14 at 11:01
  • Why does that mean you'd need to use a non-standard format in your XML? That's a non-sequitur, IMO. (As an aside, you might want to check out my [Noda Time](http://nodatime.org) project for a greater variety of date/time types, including "just date" - but that won't change whether or not it's a good idea to use a US-centric date format in XML...) – Jon Skeet Nov 14 '14 at 11:04
  • Sorry if I made myself unclear. My point is not to use US date format. The point is to omit time parts of C# `DateTime` type in responses. I made it for JSON and want same result in XML for consistensy. – UserControl Nov 14 '14 at 11:08
  • Right, so are you going to use `yyyy-MM-dd`? Your example of code to force JSON to use a US-centric format is confusing the matter. I suspect there may be an XML serialization attribute to say specifically "this is just a date" at which point you don't need to specify a format... – Jon Skeet Nov 14 '14 at 11:10
  • I suspect you want to follow the *second* answer at http://stackoverflow.com/questions/1118833, i.e. specify `[XmlElement(DataType=date)]` – Jon Skeet Nov 14 '14 at 11:11
  • That's it! It does work if I set `config.Formatters.XmlFormatter.UseXmlSerializer` to `true`. Can you please post it as an answer? – UserControl Nov 14 '14 at 11:20

1 Answers1

1

You shouldn't specify your own format - you should instead tell the XML serializer that the value is just meant to be a date, using:

[XmlElement(DataType="date")]

Then force the use of XML serializer with config.Formatters.XmlFormatter.UseXmlSerializer = true and you should be fine. That way you'll be using the standard (ISO-8601) format for dates, which is yyyy-MM-dd... which means standard tools (e.g. LINQ to XML) will be able to parse the XML appropriately.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194