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

  • 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 9, 2015 at 16:01

2 Answers 2


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:

public DateTime DoNotSerialize {get;set;}

public string ProxyDateTime {
    get {return DoNotSerialize.ToString("yyyyMMdd");}
    set {DoNotSerialize = DateTime.Parse(value);}
  • 13
    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 7, 2014 at 17:47
  • 1
    @spamguy: XmlSerializer only handles public properties with both a public get and public set. Feb 7, 2014 at 18:26

XmlElementAttribute#DataType should provide what you need:

public DateTime Date1 {get;set;}

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

  • 3
    No, the problem is that I needed to serialize it to a non-standard xml date format. The accepted solution is what I went for.
    – cjk
    Feb 17, 2011 at 11:13
  • 1
    This doesn't work for me, gives a build error. [XmlElement(DataType="date")] works. Jul 17, 2013 at 9:07
  • Thanks. Fixed my problem. I was trying to remove the Time component. Cheers! Apr 1, 2014 at 6:44
  • Works great if you need YYYY-MM-DD, which I actually need DD/MM/YYYY, Doh! Jul 15, 2020 at 6:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.