JamesNK / Newtonsoft.Json.Bson

Json.NET BSON adds support for reading and writing BSON to Json.NET
MIT License
55 stars 23 forks source link

DateTime objects with sub-millisecond timestamps are being rounded to the millisecond #12

Closed lukegeor closed 6 years ago

lukegeor commented 6 years ago

If you run the code below, you'll see that the two lines written to the console are not the same. The DateTime is being rounded to the nearest millisecond.

DateTime d = new DateTime(123456789012);
Console.WriteLine(d.Ticks);
var serializer = new JsonSerializer();
byte[] buffer;

using (MemoryStream ms = new MemoryStream())
{
    using (BsonDataWriter w = new BsonDataWriter(ms))
    {
        serializer.Serialize(w, new List<DateTime>() { d });
        ms.Position = 0;
        buffer = ms.ToArray();
    }
}
using (MemoryStream ms = new MemoryStream(buffer))
{
    using (BsonDataReader r = new BsonDataReader(ms))
    {
        r.ReadRootValueAsArray = true;
        var d2 = (List<DateTime>)serializer.Deserialize(r, typeof(List<DateTime>));
        Console.WriteLine(d2[0].Ticks);
    }
}
lukegeor commented 6 years ago

Never mind. Looks like that's part of the BSON spec.