I have three different Dates, in this format:
long firstDate = System.currentTimeMillis();
long secondDate = System.currentTimeMillis();
long thirdDate = System.currentTimeMillis();
The firstDate is the starting point.
I want the seconds milliseconds that have passed between the starting point and to the others.
Example:
firstDate = 0.000
secondDate= 1.234
thirdDate = 2.345
CodePudding user response:
First, understand that System.currentTimeMillis
was supplanted years ago by java.time.Instant
.
Instant x = Instant.now() ;
Calculate elapsed time with Duration
.
Duration d = Duration.between ( x , y ) ;
Tip: To represent each span of time, add the ThreeTen-Extra library to your project for its Interval
class.
CodePudding user response:
final long totalDiffInMillis = thirdDate - firstDate;
final String diffSeconds = new DecimalFormat("#").format(totalDiffInMillis / 1000);
final long diffMillis = totalDiffInMillis % 1000;
System.out.printf("Diff between thirdDate and firstDate: %s seconds, %d milliseconds",
diffSeconds,
diffMillis);
CodePudding user response:
For your case, you can use Stopwatch from Google Guava.