Can you specify format for XmlSerialization of a datetime?

C#XmlSerialization

C# Problem Overview


I need to serialize / deserialize a datetime into yyyyMMdd format for an XML file. Is there an attribute / workaround I can use for this?

C# Solutions


Solution 1 - C#

No, there isn't. If it's in that format, then it's not a valid dateTime as far as XML Schema is concerned.

The best you can do is as follows:

[XmlIgnore]
public DateTime DoNotSerialize {get;set;}

public string ProxyDateTime {
    get {return DoNotSerialize.ToString("yyyyMMdd");}
    set {DoNotSerialize = DateTime.Parse(value);}
}

Solution 2 - C#

XmlElementAttribute#DataType should provide what you need:

[XmlElement(DataType="date")]    
public DateTime Date1 {get;set;}

This will get Date1 property serialized to the proper xml date format.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncjkView Question on Stackoverflow
Solution 1 - C#John SaundersView Answer on Stackoverflow
Solution 2 - C#th2tranView Answer on Stackoverflow