ThaMe90
ThaMe90

Reputation: 4296

How can I get the current time in Java correctly?

What is the corresponding Java code for this piece of C# code?

public static readonly DateTime Epoch = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long Now
{
    get { return (long)(DateTime.UtcNow - Epoch).TotalMilliseconds; }
}

I know I could calculate this with a Date object, but isn't the Calendar from Java different from how C#'s DateTime?

At the moment I use this piece o' Java:

public static long getCurrentTimeMillis(){
    TimeZone here = TimeZone.getDefault();
    Time time = new Time(here.toString());
    time.setToNow();
    return time.toMillis(false);
}

But the differences between the two pieces of code are significant... The C# code has over 1.5 million milliseconds more then the Java code... How could I get the correct time in milliseconds from the Java code?

Upvotes: 1

Views: 2827

Answers (3)

Erik
Erik

Reputation: 91260

Use this:

System.currentTimeMillis()

This is unixtime with millisecond resolution, aka milliseconds since midnight Jan 1 1970, the epoch

Convert this to your alternative epoch:

long Offset = new Date(100, 0, 1, 0, 0, 0).getTime();
long DotNetTime = System.currentTimeMillis() - Offset;

Of course, calculating this offset once and making it a constant would be advisable.

Upvotes: 9

CloudyMarble
CloudyMarble

Reputation: 37566

Try

System.currentTimeMillis()

Upvotes: 1

ajm
ajm

Reputation: 13203

System.currentTimeMillis() is correct

Upvotes: 3

Related Questions