I need to serialize / deserialize a datetime into yyyyMMdd format for an XML file. Is there an attribute / workaround I can use for this?
Asked
Active
Viewed 5.7k times
60
-
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 Answers
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
-
14Worth 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.
-
3No, 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 '11 at 11:13
-
1This doesn't work for me, gives a build error. [XmlElement(DataType="date")] works. – Adam Marshall Jul 17 '13 at 09:07
-
Thanks. Fixed my problem. I was trying to remove the Time component. Cheers! – Matt Fitzmaurice Apr 01 '14 at 06:44
-
1Works great if you need YYYY-MM-DD, which I actually need DD/MM/YYYY, Doh! – Benj Sanders Jul 15 '20 at 06:31