How do I change the universal sort format of DateTime in .NET?

We are trying to get our datetime objects in C # to serialize using a different format than the default. We don't want to include milliseconds. SortableDateTimePattern and UniversalSortableDateTimePattern are read-only.

+2


source to share


2 answers


Assuming you are talking about the DateTime instances in the DataContract being sent by the server, I don't think there is an easy way to do this. The templates you mentioned are not used (if there were any, you could just hack the generic template instance with reflection for a simple and straightforward solution). The DataContractSerializer ultimately delegates the task to its internal XsdDateTime.ToString () method, which is hardcoded to always allocate fractional seconds if they are nonzero.

It's not smart, but using hardcoded behavior might be the simplest solution: just copy all your DateTimes, resetting milliseconds to zero, before leaving the server.



Alternatively, you can wire a custom IDispatchMessageFormatter or IDispatchMessageInspector to the affected operations. There are also no park walks if you want them to be versatile and easy to connect.

Just curious: Do you have a bad client who doesn't understand fractional seconds?

+1


source


I have looked at several ways to solve this problem. More sophisticated methods involve connecting a custom MessageFormatter endpoint.

We found an easy way to do this.

The fraction of seconds is generated only if the datetime object has them.

What we did:



We've created a static object for the propertychange event handler that uses reflection to define datetime data types. When we find it, we recreate the date and time without a split second. In our case, we were not interested in seconds at all. We are hooking up the event in the partial constructor of the class. Here it is.

Sure,

public static class DateTimeSecondCatcher
{
    PropertyInfo dateTimePropertyInfo = sender.GetType().GetProperty(e.PropertyName);
        if ((dateTimePropertyInfo != null) && (dateTimePropertyInfo.PropertyType == typeof(DateTime)))
        {

            DateTime dteValue = (DateTime)dateTimePropertyInfo.GetValue(sender, null);
            if (dteValue.Millisecond > 0)
            {
                dateTimePropertyInfo.SetValue(sender, new DateTime(dteValue.Year,dteValue.Month,dteValue.Day, dteValue.Hour,dteValue.Minute,dteValue.Second,0,dteValue.Kind), null);
            }
        }

}


// This code goes in the partial class constructor
this.PropertyChanged += new PropertyChangedEventHandler(DateTimeSecondCatcher.OnPropertyChanged);

      

0


source







All Articles