How to serialize DateTime correctly?

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

0001-01-01T00: 00: 00

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

startIndex cannot be greater than the length of the string.
Parameter Name: startIndex.

However, when I edit the XML manually, deserialization has been going fine for 1000 - 9999 years, but not for years <1000?

The DateTime property has [XmlElement] , like all other fields that are correctly serialized, and the rest of the code looks fine. Thanks in advance!

+3
source share
1 answer

( ), .

[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); }
    }
}

:

[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);
    }
}

:

<?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>
+5

All Articles