Skip to content

Instantly share code, notes, and snippets.

@rodrigocananea
Created July 10, 2021 01:00
Show Gist options
  • Save rodrigocananea/16427b2bda17892c98d36d55b7316408 to your computer and use it in GitHub Desktop.
Save rodrigocananea/16427b2bda17892c98d36d55b7316408 to your computer and use it in GitHub Desktop.
Java 8 Elapsed time with Guava
import com.google.common.base.Stopwatch;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import javax.swing.Timer;
/**
*
* @author Rodrigo
*/
public class ElapsedTime {
static Stopwatch stopwatch;
public static void main(String[] args) throws Exception {
stopwatch = Stopwatch.createStarted();
Timer timer = new Timer(10, new hour());
timer.start();
Thread.sleep(100);
}
private static String formatDuration(Duration d) {
long days = d.toDays();
d = d.minusDays(days);
long hours = d.toHours();
d = d.minusHours(hours);
long minutes = d.toMinutes();
d = d.minusMinutes(minutes);
long seconds = d.getSeconds();
return String.format("%02d", hours)
+ ":" + String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds);
}
public static class hour implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Duration duration = stopwatch.elapsed();
System.out.println("Elapsed time - " + formatDuration(duration));
// ... new JLabel("Elapsed time - " + formatDuration(duration));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment