Baral
Baral

Reputation: 3141

DateTime Serialization differs (SQL Server vs .Net)

I have a unit test that do the following:

  1. It creates an instance of a class (myObject).
  2. It Serializes myObject using SerializeObject (code below)
  3. It sends the object to a WCF Service which persists the object to a SQL Server Database. (INSERT)
  4. It resquests the WCF to get the object (myObject2) (SELECT)
  5. It Serializes myObject2 using SerializeObject
  6. It compares if serialization are equal.

    public static string SerializeObject<T>(this T toSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
        StringWriter textWriter = new StringWriter();
    
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
    

The problem is with the datetime field.

Expected (from UnitTest):

<dateField>2015-10-30T08:04:52.6115334-04:00</dateField>

Actual (from WCF):

<dateField>2015-10-30T08:04:52.613</dateField>

As you can see, first there seems to be a problem with the precision. Also, the DateTime from the Unit Test has -04:00 in it.

How can I have those two dates match?

Upvotes: 1

Views: 69

Answers (2)

Baral
Baral

Reputation: 3141

I was not able to fix that issue. I just set the date back to its value in c# and it works fine.

Upvotes: 0

Cameron
Cameron

Reputation: 2594

I'm not sure how to correct the issue with precision of the DateTime.

As for the issue with the -4:00 that's the timezone. WCF does some funny stuff with timezones (Feel free to research WCF DateTime TimeZones for more information). So you'll either want to convert to UTC to store it off, then convert back to Local time on the client, or you can tell the DateTime to not specify what kind the time is (Local or UTC).

The latter option is the one I'm most familiar with, and the following code should do the trick.

public static DateTime GetUnspecifiedTime(DateTime value)
{
    return DateTime.SpecifyKind(value, DateTimeKind.Unspecified);
}

Of course you could wrap it in a property setter also, which is my preferred method.

private DateTime _myDate;
public DateTime MyDate
{
    get { return _myDate; }
    set { _myDate = DateTime.SpecifyKind(value, DateTimeKind.Unspecified); }
}

Upvotes: 2

Related Questions