Handling XML dateTime fields in .NET

      Comments Off on Handling XML dateTime fields in .NET

The XML xs:dateTime format specifies that the date and time must be passed in ISO 8601 format. Also you will probably want to pass it in a time zone-independed way. The easiest way to do this is to covert the date to UTC (a.k.a. Greenwich Mean Time or “Zulu”). This can be done as follows:

public const string ISO_UTC_FORMAT = "yyyy-MM-ddTHH:mm:ss.sZ";
DateTime date;
XmlWriter w;
String s = date.ToUniversalTime().ToString(ISO_UTC_FORMAT);
w.WriteString(s);

The other thing to be careful about is never to use XmlReader.ReadElementStringAsDateTime() to read this data. At least in Framework 3.0 (an probably earlier) it will IGNORE THE TIME ZONE INDICATOR. Instead use

XmlReader r;
DateTime dt = DateTime.Parse(r.ReadElementString());

The standard DateTime.Parse() handles the ISO format correctly.