TimeSpan milliseconds are not being serialized / deserialized correctly

It appears that TimeSpan milliseconds are not being serialized / deserialized correctly. I see the same behavior from ServiceStack.Text for version 4.5.4 and 4.5.8.


The following test demonstrates the issue I’m see.

    [Test]
    public void ServiceStack_Timespan_Text()
    {
        Assert.Multiple(() =>
        {
            for (int i = 1; i <= 999; i++)
            {
                TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, i);
                string json = JsonSerializer.SerializeToString(timeSpan);
                TimeSpan timeSpanAfter = JsonSerializer.DeserializeFromString<TimeSpan>(json);
                Assert.AreEqual(TimeSpan.FromMilliseconds(i), timeSpanAfter);
            }
        });
    }

They’re floating point rounding issues after serializing to and from the TimeSpan string format.

I have tested the following serializers and they all pass the previously posted unit test. There must be a bug in the ServiceStack.Text timespan serialization implementation. This is a huge issue for us.

  • Newtonsoft.Json
  • DataContractSerializer
  • DataContractJsonSerializer

FYI a quick solution is to change to use the standard TimeSpan format, i.e:

JsConfig.TimeSpanHandler = TimeSpanHandler.StandardFormat;

I’ll look to see if we can prevent the rounding errors with the default XSD duration format.

This issue should now be resolved from this commit which is available from v4.5.9 that’s now available on MyGet.