Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent DateTime from including zone offset in SOAP xsd:dateTime element?

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</startDate>
<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?

like image 950
Joseph Bui Avatar asked Oct 29 '08 18:10

Joseph Bui


2 Answers

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.

like image 173
Joe Avatar answered Oct 06 '22 00:10

Joe


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.

like image 27
Dan Finucane Avatar answered Oct 05 '22 23:10

Dan Finucane