java.time
Instant startTime = Instant.now();
Duration diff = Duration.between(startTime, Instant.now());
System.out.println("Difference in seconds: " + diff.getSeconds());
This snippet just printed:
Difference in seconds: 0
This is as expected since there isn’t a full second between the two calls to Instant.now()
.
What went wrong in your code?
You were calculating the difference in milliseconds between your two Date
objects correctly. You did not print the difference and therefore never saw that it was correct. And you did not convert it to seconds.
To illustrate the first point I added this line to your code:
System.out.println("diff (milliseconds):: " + diff);
Then I got this output from it:
hangupClicked New Time :: 1537890219204 :: 1537890219204
diff (milliseconds):: 0
That said, you shouldn’t use Date
in 2018. That class is long outdated and poorly designed at the same time. You should prefer to use java.time, the modern Java date and time API.
Links