Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing milliseconds from timestamp when deserializing to object using JSON.net

If I deserialize a timestamp contained in json to an object it loses it's millisecond precision.

var json = "{\"timestamp\":\"2016-06-16T16:27:36.808Z\"}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Console.WriteLine(dict["timestamp"]);

Output:

16/06/2016 16:27:36

This happens even if I convert the object to a DateTime.

var obj = dict["timestamp"];
var timestamp = DateTime.Parse(obj.ToString());
Console.WriteLine(timestamp.ToString("yyyy/MM/dd HH:mm:ss.ffff"));

Output:

2016/06/16 16:27:36.0000
like image 284
Scott Avatar asked Dec 25 '22 04:12

Scott


1 Answers

The issue is merely that you are calling ToString on the DateTime in both cases and the default string representation does not include milliseconds, so they are lost.

Changing the last line of the first snippet:

var json = "{\"timestamp\":\"2016-06-16T16:27:36.808Z\"}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Console.WriteLine(((DateTime)dict["timestamp"]).ToString("O"));

Gives

2016-06-16T16:27:36.8080000Z

"O" is the round-trip format that includes full precision. You may wish to use a different format.

like image 131
Mike Zboray Avatar answered Dec 27 '22 12:12

Mike Zboray