60

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

cjk
  • 45,739
  • 9
  • 81
  • 112
  • You can manipulate the getter and setter of the variable. For example I had an enum Sex{Unknown, Female, Male} and I had a string setter which formattet m into male and f into female. The xml serializer also wrote f and m inseatd of the full enum name. Worked fine but there's nearly no practical usage for this. – BlueWizard Aug 09 '15 at 16:01

2 Answers2

72

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);}
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 14
    Worth noting: both a get/set must be present. I spent a half hour debugging why my property wasn't being serialized. It turns out I had no 'set', because I thought to myself, 'I'll never be changing this value; why bother writing a set?' – spamguy Feb 07 '14 at 17:47
  • 2
    @spamguy: XmlSerializer only handles public properties with both a public get and public set. – John Saunders Feb 07 '14 at 18:26
22

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.

Peter
  • 37,042
  • 39
  • 142
  • 198
th2tran
  • 321
  • 2
  • 4