tags:

views:

330

answers:

4

I have this Java code, and I want to do the same thing in C#:

long now =System.currentTimeMillis()/1000;
A: 

Ticks maybe?

leppie
+7  A: 

Having checked what java returns (1970/1/1 etc):

static readonly DateTime epoch=new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc);
...
long ms = (long)(DateTime.UtcNow - epoch).TotalMilliseconds;
long result = ms / 1000;
Marc Gravell
Isn't that 19700101 in your local timezone? The Java value is since 19700101Z000000 (UTC).
MSalters
Note that the epoch is local too... but I'll edit to account for it...
Marc Gravell
A: 

currenTimeMillis gives the number of milliseconds since 1. Jan 1970, so if you need the exact same answer you want something like:

((DateTime.Now - new DateTime(1970,1,1)).TotalMilliseconds) / 1000
Stuart Dunkeld
+1  A: 

There's no direct equivalent to this in C# (and by that I mean in a single line), but assuming you just want something functionally similar, but not necessarily the Java implementation you can use:

DateTime.Now.Ticks;

Ticks are:

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue.

http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

And this may not be relevant to you at all, but getting time in ticks/ms is often used for microbenchmarks to measure how long something takes in your code, and C# has a better class for that, namely Stopwatch. It's easier to use and more accurate too.

Use it like:

Stopwatch s = Stopwatch.StartNew();
s.Stop();
Console.Write(s.Elapsed);

This may not be what you're trying to do, but useful to know anyway.

JulianR
that's good btw :)