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 J开发者_如何学JAVAava code?
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.
System.currentTimeMillis() is correct
Try
System.currentTimeMillis()
精彩评论