简体   繁体   English

如何正确序列化 DateTime?

[英]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当我对 DateTime 字段(具有来自日期选择器的值)进行 XML 序列化时,日期始终序列化为

0001-01-01T00:00:00 0001-01-01T00:00:00

ie 1st January 1AD.即公元 1 月 1 日。 Why is this?为什么是这样? Also, when I try to deserialize the XML, I get this error:此外,当我尝试反序列化 XML 时,我收到此错误:

startIndex cannot be larger than length of string. startIndex 不能大于字符串的长度。
Parameter name: startIndex.参数名称:startIndex。

However, when I edit the XML manually, deserialization goes just fine for years 1000-9999, but not for years <1000?但是,当我手动编辑 XML 时,反序列化在 1000-9999 年就可以正常进行,但对于 <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. DateTime 属性具有[XmlElement] ,就像所有其他正确序列化的字段一样,并且代码的 rest 似乎没问题。 Thanks in advance!提前致谢!

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:产生以下 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM