Kaikus
Kaikus

Reputation: 1095

Force local DateTime serialization

I'm serializing a DateTime value, and it works OK, creates an ISODateTime value. But it is always serializing using UTC.

YYY-MM-DDThh:mm:ss+hh:mm:ss

When I create the DateTime instance, I force LocalTime:

 DateTime localDateTime = new DateTime(DateTime.Now.Ticks,DateTimeKind.Local);

But, for some reason it always serializes to UTC (I always get '+01:00' at the end). It is supposed to automatically read get DataTimeKind and serialize properly, but no... :(

How do I configure the serializer or the attribute to force the DateTime to be serialized in Local Time?

EDIT: This is a test class

[Serializable]
public class DateTimeTest
{
    [System.Xml.Serialization.XmlElement("DateTime")]
    public DateTime dateTime;
}

This is serialization code

    public static string XMLSerializeToString<ObjectType>(ObjectType objetToSerialize, string defaultNamespace)
    {
        TextWriter stringWriter = new StringWriter();
        XmlSerializer serializer =
            defaultNamespace==null ? new XmlSerializer(typeof(ObjectType)) : new XmlSerializer(typeof(ObjectType),defaultNamespace);
        serializer.Serialize(xmlWriter, objetToSerialize);
        return stringWriter.ToString();
    }

This is callin' the serializer

    DateTime localDateTime = new DateTime(DateTime.Now.Ticks, DateTimeKind.Local);
    DateTimeTest dateTimeTest = new DateTimeTest();
    dateTimeTest.dateTime = localDateTime;
    string ser = XMLProcessor.XMLSerializeToString<DateTimeTest>(dateTimeTest, null);

This is the resulting string

<?xml version="1.0" encoding="utf-16"?>
<DateTimeTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DateTime>2013-10-25T17:01:35.7228+01:00</DateTime>
</DateTimeTest>

I dont want to get 17:01:35+01:00. I want to get 17:01:35. How can I get it?

Thanks :)

Upvotes: 3

Views: 2970

Answers (1)

to StackOverflow
to StackOverflow

Reputation: 124746

As I said in a comment:

You haven't said what serializer you're using, but you might try setting its Kind to DateTimeKind.Unspecified if you don't want to see the timezone offset.

Your code to set the DateTime:

DateTime localDateTime = new DateTime(DateTime.Now.Ticks, DateTimeKind.Local);

is unnecessarily unwieldly, being exactly equivalent to:

DateTime localDateTime = DateTime.Now;

If you want a date time that will serialize without an offset, it needs to have DateTimeKind.Unspecified:

DateTime localDateTime = DateTime.Now.SpecifyKind(DateTimeKind.Unspecified);

Upvotes: 2

Related Questions