What is the correct format to use for Date/Time in an XML file

前端 未结 5 1070
温柔的废话
温柔的废话 2020-11-27 15:50

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?

相关标签:
5条回答
  • 2020-11-27 16:21

    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.

    0 讨论(0)
  • 2020-11-27 16:30

    EDIT: This is bad advice. Use "o", as above. "s" does the wrong thing.

    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/xml/schema_dtypes_date.asp

    0 讨论(0)
  • 2020-11-27 16:31

    If you are manually assembling the XML string use var.ToUniversalTime().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.

    0 讨论(0)
  • 2020-11-27 16:33

    The XmlConvert class provides these kinds of facilities. About DateTimes, in particular, be careful about obsolete methods. See also: https://stackoverflow.com/a/7457718/1288109

    0 讨论(0)
  • 2020-11-27 16:36

    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' between the date and time: 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.

    0 讨论(0)
提交回复
热议问题