CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Brendan Tompkins [MVP]

Blog First. Ask Questions Later.

Nice Fix for System.TimeSpan Serialization

If you've tried to XML serialize a System.TimeSpan value, you may have noticed that your node is null, no matter what you set the TimeSpan value to be. There's a nice workaround to this posted here by  Ben Lucas.  Basically, you [XmlIgnore] your object's TimeSpan property, and add another that serializes the time span's ticks.  Pretty simple, but works great!

[XmlIgnore]public System.TimeSpan TimeToBeReceived
{
  get { return timeToBeReceived;}
 
set
  
{
         
if (timeToBeReceived == value) return;
          timeToBeReceived =
value;
   }
}

public long TimeToBeReceivedTicks
{
  
get { return timeToBeReceived.Ticks; }
  
set { this.timeToBeReceived = new TimeSpan(value); }
}

So instead of this:

<TimeToBeReceived />

You get this:

<TimeToBeReceivedTicks>864000000000</TimeToBeReceivedTicks>

Thanks Ben!

-Brendan

 

 



Comments

vb set timespan value said:

Pingback from  vb set timespan value

# April 30, 2008 5:05 AM

Bubba Man said:

Thanks!

That was a huge help.

I did not even know that problem existed until about a 1/2 an hour ago. Very handy.

# May 12, 2008 5:22 PM

S. Gryphon said:

Yep.

Another alternative is to use the XmlConvert class (msdn.microsoft.com/.../system.xml.xmlconvert.totimespan.aspx) and send/receive values that conform to the XSD duration data type. Using duration may be better thank ticks if you want to conform to XML standards.

e.g.

public long TimeToBeReceivedDuration

{

  get { return XmlConvert.ToString(timeToBeReceived); }

  set { this.timeToBeReceived = XmlConvert.ToTimeSpan(value); }

}

# June 18, 2008 10:08 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Brendan Tompkins

Brendan has been programming with .NET since the first public beta and is owner and operator of Port Technology Services, a consultancy company providing .NET application development services to the Maritime industry. In July, 2007, he was awarded the Microsoft MVP award for ASP.NET. He's also a proud co-founder of failed .COM startup Intrinsigo, and has had a hand in the failure of numerous other businesses. He currently runs CodeBetter.Com and Devlicio.us, and lives in Norfolk, Virgina with his wife Tiara and son Ian.

View Brendan's profile on LinkedIn

Check out Devlicio.us!

Our Sponsors