Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

how to calculate difference between two DateTime in ms?

According to msdn DateTime precision is 10 ms. So t2-t1 precision in the example below is also 10 ms. However the returned value is "double" what is confusing.

DateTime t1 = DateTime.Now; // precision is 10 ms
....
DateTime t2 = DateTime.Now; // precision is 10 ms
... (t2-t1).TotalMilliseconds; // double (so precision is less than 1 ms???)

I expect int value because double value doesn't make sense when precision is 10 ms. I need to use resulted value in Thread.Sleep(). Should I just cast to int?

Upvotes: 4

Views: 522

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503290

The precision of DateTime itself is down to the tick.

The granularity of DateTime.Now is typically 10 or 15ms - it's the granularity of the system clock. (That doesn't mean the clock is accurate to the nearest 10 or 15ms, mind you.) The subtraction operator on DateTime shouldn't know or care about that though - the result is just a TimeSpan which again has a precision to the tick level.

Just casting to int should be absolutely fine.

(You might want to read Eric Lippert's blog post on this, by the way.)

Upvotes: 7

Related Questions