Java System.currentTimeMillis() equivalent

  • Thread starter Thread starter AzenAlex
  • Start date Start date
And if you divide the number from Ticks by 10000 you get milliseconds.

so for example if what you wanted to do was time something, you could do:

long ticks = DateTime.Now.Ticks;
System.Threading.Thread.Sleep(20000);
Console.WriteLine((DateTime.Now.Ticks - ticks)/10000);

and it will correctly rprint 20000 (maybe plus a few milliseconds because of
the brief time it took to do the actual console.writeline)
 
MrNobody said:
And if you divide the number from Ticks by 10000 you get milliseconds.

so for example if what you wanted to do was time something, you could do:

long ticks = DateTime.Now.Ticks;
System.Threading.Thread.Sleep(20000);
Console.WriteLine((DateTime.Now.Ticks - ticks)/10000);

and it will correctly rprint 20000 (maybe plus a few milliseconds because of
the brief time it took to do the actual console.writeline)

However, you need to do extra translation to actually give the
equivalent of System.currentTimeMillis, as that is:

a) based on UTC
b) Since 1970, not 1AD



Here's an equivalent (tested by running a Java program and the C#
equivalent in close proximity - not tested for timezones as I'm in
GMT...)


static readonly DateTime Epoch = new DateTime (1970, 1, 1);
static long CurrentTimeMillis()
{
return (long)(DateTime.UtcNow-Epoch).TotalMilliseconds;
}
 
...
I think what you want is:

DateTime.Now.Ticks

But it's not that simple...

There's at least three things to consider here:

1. DateTime.Ticks is in *100ds of nanoseconds*, not milliseconds.

2. A major difference between the Java way and the .NET way of handling
dates is that DateTime.Now yields a *local* date, while the Java Date
internally is a UTC date. This means that you want to use the
DateTime.UtcNow.Ticks instead.

3. But this isn't enough to compare with the milliseconds in the Java Date,
as Java and .NET uses different epochs; Java uses 1970-01-01, while .NET
uses 0001-01-01


/// Bjorn A
 
thanks guys,

I kind of combined both ideas and it seems to work.

DateTime UtcNow = DateTime.UtcNow.Ticks;
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
long timeStamp = (UtcNow - baseTime).Ticks / 10000;
 
I kind of combined both ideas and it seems to work.

DateTime UtcNow = DateTime.UtcNow.Ticks;
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
long timeStamp = (UtcNow - baseTime).Ticks / 10000;

Why rely on a constant which isn't terribly obvious when the
TotalMilliseconds makes it absolutely clear what the units returned
are?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top