开发者

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

开发者 https://www.devze.com 2023-04-07 13:37 出处:网络
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 respec

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

精彩评论

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