"Use DateTimeOffset
" is usually good advice, but part of the problem can be that when classes are auto-generated from WSDL (either with WCF or .asmx) , the xs:DateTime
types in XSD get created as DateTime
objects. So - can't.
Unfortunately, there is no good solution for this. If you actually try to use DateTimeOffset
in your models at the source, the WSDL gets a weird complex object. If you try to just change the receiving side, it can't deserialize an xs:DateTime
into a DateTimeOffset
.
This is a weakness of WCF, SOAP, and XSD. Read more in WCF DateTimeOffset compatibility.
The only workarounds when populating the data are to have the DateTime
fields explicitly set to either local or UTC kind. You can use DateTime.SpecifyKind
, or any of the conversion functions such as ToLocalTime
, ToUniversalTime
, or similar methods from TimeZoneInfo
. Just be very careful if you decide to use local time, as taking the time zone from the server is usually not a great idea. It would be best to transmit in terms of universal time.
If you're just filling it with the current time, then use DateTime.UtcNow
. If you're loading a UTC-based DateTime
from your database, then use DateTime.SpecifyKind
with DateTimeKind.Utc
. If you already have a DateTimeOffset
, then you can use the .UtcDateTime
property to assign it to a DateTime
value in your model.
If DateTimeOffset
were supported properly, then the offset could be arbitrarily anything. But since it's not - you're limited to what you can express with DateTimeKind
.