Brendan Tompkins

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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

 

 


Posted Tue, Aug 10 2004 9:07 AM by Brendan Tompkins

[Advertisement]

Comments

Brett wrote re: Nice Fix for System.TimeSpan Serialization
on Thu, Feb 17 2005 12:40 PM
Wow. Very handy, thank's for reposting!
vb set timespan value wrote vb set timespan value
on Wed, Apr 30 2008 5:05 AM

Pingback from  vb set timespan value

Bubba Man wrote re: Nice Fix for System.TimeSpan Serialization
on Mon, May 12 2008 5:22 PM

Thanks!

That was a huge help.

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

S. Gryphon wrote re: Nice Fix for System.TimeSpan Serialization
on Wed, Jun 18 2008 10:08 PM

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); }

}

S?rialisation d'un objet TimeSpan | hilpers wrote S?rialisation d'un objet TimeSpan | hilpers
on Thu, Jan 22 2009 11:24 AM

Pingback from  S?rialisation d'un objet TimeSpan | hilpers

Uoynkzdj wrote re: Nice Fix for System.TimeSpan Serialization
on Tue, Jul 14 2009 4:23 PM

CpIGcP

marc wrote re: Nice Fix for System.TimeSpan Serialization
on Tue, Aug 18 2009 6:17 AM

nice. Any idea what's the problem behind this? Is the timespan not specified in XML?

Add a Comment

(required)  
(optional)
(required)  
Remember Me?