views:

2152

answers:

2

I have this in some WSDL:

<element name="startDate" type="xsd:dateTime"/>
<element name="endDate" type="xsd:dateTime"/>

Which results in the following text in the SOAP envelope:

<startDate>2008-10-29T12:01:05</endDate>
<endDate>2008-10-29T12:38:59.65625-04:00</endDate>

Only some times have the milliseconds and zone offset. This causes me a headache because I'm trying to get a range of 37 minutes and 54 seconds in this example, but because of the offset I end up with 4 hours, 37 minutes, 54.65625 seconds. Is this some kind of rounding error in DateTime? How do I prevent this from happening?

A: 

What are you using to generate the date? If you are building this XML in your code rather than using some serializer (WCF or XmlSerializer) you could use System.Xml.XmlConvert to generate and interpret the date as follows:

To create the string to put in the XML:

DateTime startDate = DateTime.Now;
string startDateString = System.Xml.XmlConvert.ToString(startDate);

To get the date out of the XML:

DateTime startDateFromXml = System.Xml.XmlConvert.ToDateTime(startDateString);

If you start with two DateTime instances that differ by 37 minutes and 54 seconds before you push them into XML they will still differ by 37 minutes and 54 seconds after you pull them out of the XML.

Dan Finucane
+2  A: 

I suspect your endDate value has the Kind property set to DateTimeKind.Local.

You can change this to DateTimeKind.Unspecified as follows:

endDate = DateTime.SpecifyKind(endDate, DateTimeKind.Unspecified)

after which I believe it will be serialized without the timezone offset.

Note that you will get a DateTime with DateTimeKind.Local if you have initialized it using DateTime.Now or DateTime.Today, and DateTimeKind.Utc if you have initialized it using Datetime.UtcNow.

Joe