Matt
Matt

Reputation: 521

How do I serialize DateTime properly?

When I XML-serialize my DateTime field (which has the value from a datepicker), the date is always serialized as

0001-01-01T00:00:00

i.e. 1st January 1AD. Why is this? Also, when I try to deserialize the XML, I get this error:

startIndex cannot be larger than length of string.
Parameter name: startIndex.

However, when I edit the XML manually, deserialization goes just fine for years 1000-9999, but not for years <1000 ?

The DateTime property has the [XmlElement], just like all other fields that get serialized properly, and the rest of the code appears to be ok. Thanks in advance!

Upvotes: 4

Views: 23005

Answers (1)

Arnaud F.
Arnaud F.

Reputation: 8462

If you want to serialize it easily (and masterize the serialization of it), use a proxy field.

[Serializable]
public class Foo
{
    // Used for current use
    [XmlIgnore]
    public DateTime Date { get; set; }

    // For serialization.
    [XmlElement]
    public String ProxyDate
    {
        get { return Date.ToString("<wanted format>"); }
        set { Date = DateTime.Parse(value); }
    }
}

Edit

The following code :

[Serializable]
public class TestDate
{
    [XmlIgnore]
    public DateTime Date { get; set; }

    [XmlElement]
    public String ProxyDate
    {
        get { return Date.ToString("D"); }
        set { Date = DateTime.Parse(value); }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        TestDate date = new TestDate()
        {
            Date = DateTime.Now
        };

        XmlSerializer serializer = new XmlSerializer(typeof(TestDate));
        serializer.Serialize(Console.Out, date);
    }
}

produces the following output:

<?xml version="1.0" encoding="ibm850"?>
<TestDate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:
//www.w3.org/2001/XMLSchema">
  <ProxyDate>mardi 14 juin 2011</ProxyDate>
</TestDate>

Upvotes: 7

Related Questions