如何正确序列化DateTime?

Mat*_*att 4 c# xml serialization datetime

当我对我的DateTime字段(具有来自datepicker的值)进行XML序列化时,日期始终被序列化为

0001-01-01T00:00:00

即1月1日1日.为什么是这样?此外,当我尝试反序列化XML时,我收到此错误:

startIndex不能大于字符串的长度.
参数名称:startIndex.

但是,当我手动编辑XML时,反序列化在1000-9999年就可以了,但不是多年<1000?

DateTime属性具有[XmlElement],就像所有其他正确序列化的字段一样,其余代码似乎没问题.提前致谢!

Arn*_* F. 7

如果要轻松序列化(并掌握其序列化),请使用代理字段.

[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); }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

以下代码:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

<?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>
Run Code Online (Sandbox Code Playgroud)