.NET Framework - Convert ticks to milliseconds

Asked By Praveen on 13-Jul-07 05:08 AM
how to convert DateTime.UtcNow.ticks to Milliseconds

Marc Gravell replied on 13-Jul-07 05:22 AM
long ms1 = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;

Nicholas Paldino [.NET/C# MVP] replied on 13-Jul-07 11:24 AM
Even better would be to use the constructor of the TimeSpan class which
encapsulates the logic, and takes it out of your hands:

TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks);
double ms = ts.TotalMilliseconds;

- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
arn replied on 14-Jul-07 08:15 PM
It encapsulates the logic. But the only case where
it encapsulate better than /TimeSpan.TicksPerMillisecond
is if the correlation between Ticks and Milliseconds are
changed to something non proportional. I very much doubt
that would happen.

Ebbe Kristensen replied on 16-Jul-07 07:12 AM
You are right only if ticks are not dependent on processor clock frequency.

If they are, do remember that lowering the clock frequency to save power is
becoming widely used in portable devices.

Marc Gravell replied on 16-Jul-07 07:31 AM
In this context, a tick is defined as 100 nanoseconds. It is not
machine dependent.

I would expect lots of pain if this ever changed...

Ebbe Kristensen replied on 16-Jul-07 09:43 AM
So the value of 'TimeSpan.TicksPerMillisecond' is always 10 no matter what
system, you are working with? Is it guaranteed that it will be 10 in future

Yes, it could create non-trivial problems :-)

Marc Gravell replied on 16-Jul-07 10:48 AM
I do not know how to answer that directly, but *at the minimum* I
strongly doubt that it would ever change to be non-proportional wrt
time; anybody with a more formal answer?

arn replied on 21-Jul-07 07:06 PM
It does not need to be constant over time for the division to be
valid. The division only requires the relationship between ticks
and time to be proportional.