1

I am consuming an XML webservice with XSD elements such as:

<xs:element nillable="true" type="xs:dateTime" name="ENDDATE"/>

XML might look like the following:

<ENDDATE>2016-08-01T18:35:49+04:00</ENDDATE>

I used XSD.exe to autogenerate C# classes, when I inspect these the DateTime object will contain the time in system-local time, with Kind==Local.

Is there a way I can force the DateTime instances to be in UTC time without manually hacking the auto-generated classes for every such field (there are rather a lot)?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

1 Answers1

2

I think that you can't tune this behavior using XSD (see here). So you should update(hack) auto-generated classes and do something like described there:

[XmlIgnore()]
public DateTime Time { get; set; }

[XmlElement(ElementName = "Time")]
public string XmlTime
{
    get { return XmlConvert.ToString(Time, XmlDateTimeSerializationMode.RoundtripKind); }
    set { Time = DateTimeOffset.Parse(value).DateTime; }
}

Or, if you really often auto-generate those classes, you can introduce wrappers for them, which will transparently convert DateTime to UTC.

Community
  • 1
  • 1
grafgenerator
  • 679
  • 7
  • 13
  • This would work but there are perhaps 20 such cases across a few classes. A way to automate this would be excellent! – Mr. Boy Oct 17 '16 at 21:35
  • I'm afraid that there's no way to customize code generation so deeply using code generators, even 3d party tools. Just thought that for comfortable use you can write conversion using extension method, although this will still enforce you to do it explicitly any time you use DateTime properies. – grafgenerator Oct 18 '16 at 05:16