views:

2457

answers:

5

What is the equivalent of Java's System.currentTimeMillis() in C#?

A: 

The framework doesn't include the old seconds (or milliseconds) since 1970. The closest you get is DateTime.Ticks which is the number of 100-nanoseconds since january 1st 0001.

Cristian Libardo
Would (DateTime.Ticks/10000000)-(the number of seconds between 0001 and 1970) give an accurate answer?
Liam
+11  A: 

An alternative:

private static readonly DateTime Jan1st1970 = new DateTime
    (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long CurrentTimeMillis()
{
    return (long) (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
Jon Skeet
+1  A: 

the System.currentTimeMillis() in java returns the current time in milliseconds from 1/1/1970

c# that would be

public static double GetCurrentMilli()
    {
        DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0,0,DateTimeKind.Utc);
        TimeSpan javaSpan = DateTime.UtcNow - Jan1970;
        return javaSpan.TotalMilliseconds;
    }

edit: made it utc as suggested :)

Hath
DateTime.Now uses the local time, not UTC. I don't know exactly what happens when you subtract an unknown kind of DateTime from a local one, but it's best to set both of them to UTC :)
Jon Skeet
+1  A: 

Here is a simple way to approximate the Unix timestamp. Using UTC is closer to the unix concept, and you need to covert from double to long.

TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
long millis = (long)ts.TotalMilliseconds;
Console.WriteLine("millis={0}", millis);

prints:

millis=1226674125796
gimel
+4  A: 

We could also get a little fancy and do it as an extension method, so that it hangs off the DateTime class:

public static class DateTimeExtensions
{
    private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    public static long currentTimeMillis(this DateTime d)
    {
        return (long) ((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);
    }
}
Joel Coehoorn
Interesting mixture of languages you've got there ;)
Jon Skeet
Lol! I do that sometimes: have to switch back and forth between the two a lot, but normally it's in the IDE so I have instant feedback on it.
Joel Coehoorn