I have written a small program that shall print the difference between two Date
objects:
public static void main(final String[] args) throws Exception {
final DateFormat df = new SimpleDateFormat("HH:mm:ss.SSSSSS");
final Date start = Calendar.getInstance().getTime();
Thread.sleep(1000);
final Date end = Calendar.getInstance().getTime();
final long startMilliseconds = start.getTime();
final long endMilliseconds = end.getTime();
final long runtimeMilliseconds = endMilliseconds - startMilliseconds;
final Date runtime = new Date(runtimeMilliseconds);
System.out.print("Start : " + df.format(start));
System.out.println("\t Milliseconds: " + startMilliseconds);
System.out.print("End : " + df.format(end));
System.out.println("\t Milliseconds: " + endMilliseconds);
System.out.print("Runtime: " + df.format(runtime));
System.out.println("\t Milliseconds: " + runtimeMilliseconds);
System.out.println();
System.out.println("Milliseconds from new Date object: " + runtime.getTime());
}
It gives the following output:
Start : 13:24:54.000871 Milliseconds: 1408015494871
End : 13:24:55.000871 Milliseconds: 1408015495871
Runtime: 01:00:01.000000 Milliseconds: 1000
Milliseconds from new Date object: 1000
The difference between the milliseconds is correct, but the newly created Date
object has an extra hour added. The expected output for the runtime
object would be: 00:00:01.000000
. I think this is because of my timezone (GMT+1). How can I compute the difference between two Date
objects and get a new Date
object, that does not include the extra hour, back? I do not want to use Joda-Time or another library.