Best practices for DateTime serialization in .NET 3.5

One big issue is that WCF serialization doesn't support xs:Date. This is a big problem as if all you want is a date, you shouldn't be forced to be concerned about time zones. The following connect issue discusses some of the problems: http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=349215

If you want to represent a point in time unambiguously, i.e. not just the date part, you can use the DateTimeOffset class if you have .NET 3.5 on both client and server. Or for interoperability, always pass date/time values as UTC.


I think the best way of doing this is to always pass the object as UTC, and convert to local time on the clients. By doing so, there is a common reference point for all clients.

To convert to UTC, call ToUniversalTime on the DateTime object. Then, on the clients, call ToLocalTime to get it in their current time zone.


As long as your web services layer and client layer use the .NET DateTime type, it should serialize and deserialize properly as an SOAP-standard local date/time w/ Timezone information such as:

2008-09-15T13:14:36.9502109-05:00

If you absolutely, positively must know the timezone itself (i.e. the above could be Eastern Standard Time or Central Daylight Time), you need to create your own datatype which exposes those pieces as such:

[Serializable]
public sealed class MyDateTime
{
    public MyDateTime()
    {
        this.Now = DateTime.Now;
        this.IsDaylightSavingTime = this.Now.IsDaylightSavingTime();
        this.TimeZone = this.IsDaylightSavingTime
            ? System.TimeZone.CurrentTimeZone.DaylightName
            : System.TimeZone.CurrentTimeZone.StandardName;
    }

    public DateTime Now
    {
        get;

        set;
    }

    public string TimeZone
    {
        get;

        set;
    }

    public bool IsDaylightSavingTime
    {
        get;

        set;
    }
}

then your response would look like:

<Now>2008-09-15T13:34:08.0039447-05:00</Now>
<TimeZone>Central Daylight Time</TimeZone>
<IsDaylightSavingTime>true</IsDaylightSavingTime>

UTC/GMT would be consistent in distributed environment.

One important thing is that specify the datetimeKind after populating your DateTime property with the value from database.

dateTimeValueUtcKind = DateTime.SpecifyKind(dateTimeValue, DateTimeKind.Utc);

See MSDN