Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alter output of xml serialization

web service response passes back an xml file, one element is type Date, its format has timezone info, e.g.

12-30-2010T10:00:00+1:00

my class has a field (DateTime) to receive the value, however, it simply change date to local time.

12-30-2010T10:00:00+1:00

will be converted to

12-30-2010T02:00:00 (My local time is CST).

So the original timezone info is lost. what I want is just the time ignoring timezone info, simply

12-30-2010T10:00:00

or for some way I can extract timezone info in the response, so I can adjust converted time back to original time before conversion.

Anyone know how to do this in C#?

thanks

like image 931
toosensitive Avatar asked Nov 05 '22 18:11

toosensitive


1 Answers

DateTimeOffset is like DateTime but also preserves the original timezone offset information. Unfortunately, XmlSerializer does not support DateTimeOffset (DataContractSerializer does, but it will not serialize it to the string you expect).

If you have the option too, I'd recommend you use the DateTimeOffset type and an additional string property for serialization. Here's an example:

[Serializable]
public class MyClass
{
    const string TimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz";

    [XmlElement("Time")]
    public string TimeString { get{return Time.ToString(TimeFormat);} set{Time = DateTimeOffset.ParseExact(value, TimeFormat, null);} }

    [XmlIgnore]
    public DateTimeOffset Time { get; set; }
}

Your code would interact with the Time property while XmlSerializer will effectively use the TimeString property in its place. You can then precisely control how the conversion to/from xml is handled.

If you don't want to use the DateTimeOffset type, you could modify the TimeString methods to do something else (i.e. store the time in one field and the offset in another field).

like image 176
Michael Petito Avatar answered Nov 09 '22 04:11

Michael Petito