Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 5492bd3

Browse files
committed
Change TimeSpan to use decimals to not lose precision during deserialization
1 parent 3d6609b commit 5492bd3

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/ServiceStack.Text/Support/TimeSpanConverter.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public static TimeSpan FromXsdDuration(string xsdDuration)
5454
int days = 0;
5555
int hours = 0;
5656
int minutes = 0;
57-
double seconds = 0;
57+
decimal seconds = 0;
5858
int sign = 1;
5959

6060
if (xsdDuration.StartsWith("-", StringComparison.Ordinal))
@@ -95,13 +95,13 @@ public static TimeSpan FromXsdDuration(string xsdDuration)
9595
string[] s = m[m.Length - 1].SplitOnFirst('S');
9696
if (s.Length == 2)
9797
{
98-
double millis;
99-
if (double.TryParse(s[0], out millis))
98+
decimal millis;
99+
if (decimal.TryParse(s[0], out millis))
100100
seconds = millis;
101101
}
102102
}
103103

104-
double totalSecs = 0
104+
decimal totalSecs = 0
105105
+ (days * 24 * 60 * 60)
106106
+ (hours * 60 * 60)
107107
+ (minutes * 60)

tests/ServiceStack.Text.Tests/Utils/DateTimeSerializerTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,21 @@ public void Can_Parse_TimeSpan_NSTimeSpan()
741741
Assert.That("31536000".FromJson<TimeSpan>(), Is.EqualTo(TimeSpan.FromDays(365)));
742742
Assert.That("31539661.001".FromJson<TimeSpan>(), Is.EqualTo(Time1Y1M1H1S1MS));
743743
}
744+
745+
[Test]
746+
public void Does_not_lose_precision()
747+
{
748+
Assert.Multiple(() =>
749+
{
750+
for (int i = 1; i <= 999; i++)
751+
{
752+
TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, i);
753+
string json = JsonSerializer.SerializeToString(timeSpan);
754+
TimeSpan timeSpanAfter = JsonSerializer.DeserializeFromString<TimeSpan>(json);
755+
Assert.AreEqual(TimeSpan.FromMilliseconds(i), timeSpanAfter);
756+
}
757+
});
758+
}
744759
}
745760

746761
[TestFixture]

0 commit comments

Comments
 (0)