How do I serialize DateTime properly?

21,979

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>
Share:
21,979
Matt
Author by

Matt

Updated on July 09, 2022

Comments

  • Matt
    Matt almost 2 years

    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!

  • Matt
    Matt almost 13 years
    Nope, I did all this but still it doesn't help. Serialization itself works (and workED), but the date is always saved as 1st Jan 1AD, regardless of format?
  • Arnaud F.
    Arnaud F. almost 13 years
    See my edit, works fine, no AD in generated XML, seems you have error in your code.
  • Matt
    Matt almost 13 years
    No AD in my xml either, it's 0001-01-01T00:00:00 (which is effectively 1st january of year 1AD). Obviously the link from datepicker is what's missing in my code somehow.