开发者

How to instruct XmlSerializer to serialize a DateTime instance using a particular date time pattern?

I have many types, which are (de)serialized using the XmlSerializer. My problem is that I want the ti开发者_如何学Cmestamps (DateTime instances) appearing in these types to be serialized to the respective strings using a particular date time pattern.

How do I do it?


You can't do that with DateTime. In XSD there is a specific type for dates defining a specific format. You will be violating the specification if you do that. If you want to handle some custom format use strings as properties of the object you are serializing, not dates, and format those strings however you like.


If there's specific requirement to achieve such thing you can try something like this:

        private DateTime actualDateObject;

    public string FormattedDate
    {
        get 
        {
            return actualDateObject.ToString("format");
        }

        set
        {
            DateTime.TryParse(value, out actualDateObject);
        }

    }


I would rather go Automapper route - create a parallel class with string properties for serialization only, map it somewhere with

Mapper.CreateMap<DateTime, string>().ConvertUsing<DateTimeStringTypeConverter>();

and make a converter

public class DateTimeStringTypeConverter : ITypeConverter<DateTime, string>
{
    public string Convert(ResolutionContext context)
    {
        if (context.IsSourceValueNull)
            return null;
        else
        {
            var source = (DateTime)context.SourceValue;
            return source.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
        }
    }
}

and then do map -

Mapper.Map<DateStringClass>(DateClass);

It is more work, but keeps the domain clean...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜