title: How to serialize a TimeSpan to XML
body: <p>I am trying to serialize a .NET <code>TimeSpan</code> object to XML and it is not working. A quick google has suggested that while <code>TimeSpan</code> is serializable, the <code>XmlCustomFormatter</code> does not provide methods to convert <code>TimeSpan</code> objects to and from XML.</p>
  
  <p>One suggested approach was to ignore the <code>TimeSpan</code> for serialization, and instead serialize the result of <code>TimeSpan.Ticks</code> (and use <code>new TimeSpan(ticks)</code> for deserialization). An example of this follows:</p>
  
  <pre><code>[Serializable]
  public class MyClass
  {
      // Local Variable
      private TimeSpan m_TimeSinceLastEvent;
  
      // Public Property - XmlIgnore as it doesn't serialize anyway
      [XmlIgnore]
      public TimeSpan TimeSinceLastEvent
      {
          get { return m_TimeSinceLastEvent; }
          set { m_TimeSinceLastEvent = value; }
      }
  
      // Pretend property for serialization
      [XmlElement("TimeSinceLastEvent")]
      public long TimeSinceLastEventTicks
      {
          get { return m_TimeSinceLastEvent.Ticks; }
          set { m_TimeSinceLastEvent = new TimeSpan(value); }
      }
  }
  </code></pre>
  
  <p>While this appears to work in my brief testing - is this the best way to achieve this?</p>
  
  <p>Is there a better way to serialize a TimeSpan to and from XML?</p>