kosh
kosh

Reputation: 561

Serializing .NET DateTime to Json string

I'm writing a custom Json serializer to improve the perf of my service. And yes, I did consider Json.NET, servicestack, DataContractJsonSerializer, etc before I made the decision. My objects are flat with simple .NET types and I wanted to avoid the overhead of a much bigger library.

Anyways, here is where I run into a small problem. I have the code to serialize DateTime -

    var epoch = new DateTime(1970, 1, 1, 0, 0, 0);
    sb.Append("\"\\/Date(");
    SerializeNumber((time - epoch).TotalMilliseconds, sb);
    sb.Append(")\\/\"");

And this works great, except I can't quite get it to match the default .NET Json serializer in the output.

.NET serializer 
"\\/Date(1328057884253)\\/\"
Custom serializer
"\\/Date(1328057884253.04)\\/\"

Hmm, so I tried making my conversion less precise and switching to (int)TotalSeconds instead of milliseconds and that gives me this -

.NET serializer
"\\/Date(1328054810067)\\/\"
Custom serializer
"\\/Date(1328054810)\\/\"

I'm guessing that this wouldn't be a big deal but it would be nice to get my unit tests passing against the default .NET serializer just for sanity. Any ideas?

Thanks.

Upvotes: 1

Views: 1591

Answers (2)

Renaud Dumont
Renaud Dumont

Reputation: 1806

The Property TotalMilliseconds is of type double. You could just cast it into a long instead of using the TotalSeconds method which of course doesn't return the same value...

var epoch = new DateTime(1970, 1, 1, 0, 0, 0);
sb.Append("\"\\/Date(");
SerializeNumber((long)(time - epoch).TotalMilliseconds, sb);
sb.Append(")\\/\"");

edit: as Kosh said in comments, prefer long to int to avoid capacity overflow.

Upvotes: 2

stylefish
stylefish

Reputation: 571

couldnt you just truncate the result?

Math.Truncate((time - epoch).TotalMilliseconds)

http://msdn.microsoft.com/de-de/library/c2eabd70.aspx

or maybe better round it. dont know what the JsonSerializer would do.

Math.Round((time - epoch).TotalMilliseconds, 0)

http://msdn.microsoft.com/de-de/library/75ks3aby.aspx

Upvotes: 0

Related Questions