tags:

views:

1897

answers:

4

What format do I use for Date/Time when writing to an XML file using .NET? Do I simply use DateTime.ToString(), or do I have to use a specific format?

+1  A: 

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

Tanktalus
+5  A: 

I always use this:

dateTime.ToUniversalTime().ToString("s");

This is correct if your schema looks like this:

<xs:element name="startdate" type="xs:dateTime"/>

Which would result in:

<startdate>2002-05-30T09:00:00</startdate>

You can get more information here: http://www.w3schools.com/Schema/schema_dtypes_date.asp

jonnii
Keep in mind this converts the date to UTC. When you process the date, you must convert it back to your current timezone based on locale (unless you are processing everything in UTC). Also, usually you would put a 'Z' at the end to denote the date is UTC.
Ryan
A: 

If you are manually assembling the XML string use var.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

chilltemp
jonnii's will return basicly the same result.
chilltemp
+6  A: 

I always use the ISO 8601 format, e.g. 2008-10-31T15:07:38.6875000-05:00 -- date.ToString("o"). It is the XSD date format as well. That is the preferred format and a Standard Date and Time Format string, although you can use a manual format string if necessary if you don't want the 'T' in the format: date.ToString("yyyy-MM-dd HH:mm:ss");

EDIT: If you are using a generated class from an XSD or Web Service, you can just assign the DateTime instance directly to the class property. If you are writing XML text, then use the above.

Ryan