I'm using XDocument to create an XML file, as follows:
var d = DateTime.Now;
var xDocument = new XDocument(new XElement("ThisIsADate", d));
However, the resulting XML represents the date d using the xs:datetime format (e.g. "2012-05-11T00:00:00"). That is, it includes time information.
However, my XML is meant to match my XML Schema, which defines the element as being of type "xs:date". Consequently, the file is rejected when validated against the schema, because of the extra time information.
How can I fix this? I know I could just format the date myself using ToString() with a format, but this can't be the "right" way to do it, surely. I can't be expected to know how to format a date as a valid XML date - that's the job of the XML-related parts of the framework.
Edit: please note that I do know how to format a date using ToString(), and I also know what format string would give me the right result. That's not the answer I'm looking for. I'm looking for a function/method/class that understands what an xs:date (etc.) is, and that supports those kinds of encodings.
To be clear, I'm not looking to "get it done", I'm looking to "do it right". And re-inventing the XML wheel is not "doing it right" in my book.
The data type xs:dateTime represents an instant in time. The xs:dateTime data type has the following properties: year. month. day.
For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".
Using the Current date() function to display the current date of that day.
I fixed this problem using the following class for DateElements
private class XDateElement : XElement
{
public XDateElement(XName name, DateTime Date) :
base(name, Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
{ }
}
The advantage of using a class like this is, that you have the specific date conversion only in one place.
var d = DateTime.Now;
var xDocument = new XDocument(new XDateElement("ThisIsADate", d));
As it already has been pointed out LINQ to XML is unable to produce a DateTime
value using the the xs:date
format. A DateTime
round-trips in LINQ to XML using the xs:dateTime
format and .NET does not a have a date-only type so it is not a suprise that the designers of LINQ to XML decided to only use xs:dateTime
to not complicate the API.
The only option is to format the date as a string giving you full control of the format. To correctly use the xs:date
format you need to convert the DateTime
to a string using this code:
d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
Using ToShortDateString
and/or not specifying a CultureInfo
will not produce the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With