Date formatting when serializing an object in C # (2.0)

I am xml serializing an object with a lot of properties, and I have two properties with DateTime types. I would like to format dates for serialized output. I really don't want to implement the IXmlSerializable interface and overwrite serialization for each property. Is there any other way to achieve this?

(I am using C #, .NET 2)

Thank.

+3
source share
2 answers

To serialize XML, you need to implement IXmlSerializable, not ISerializable.

However, you can get around this with the helper property and mark the properties with an DateTimeattribute XmlIgnore.

public class Foo
{
    [XmlIgnore]
    public DateTime Bar { get; set; }

    public string BarFormatted
    {
        get { return this.Bar.ToString("dd-MM-yyyy"); }
        set { this.Bar = DateTime.ParseExact(value, "dd-MM-yyyy", null); }
    }
}
+5
source

/- DateTime, ToString.

public struct CustomDateTime
{
    private readonly DateTime _date;

    public CustomDateTime(DateTime date)
    {
        _date = date;
    }

    public override string ToString()
    {
        return _date.ToString("custom format");
    }
}
+1

Source: https://habr.com/ru/post/1748323/


All Articles