Jump to content

Timer snippet [Java 8]

Recommended Posts

Because 500 timer snippets just isn't enough already.

Uses the Duration class introduced in Java 8.


Implementation example:

 Timer t = new Timer();


import java.time.Duration;
import java.time.Instant;

 * Created by Bjorn on 6/05/2015.
public class Timer {
    private Instant start;

    private static final String formatter = "%02d";

    public Timer() {

    public void reset() {
        start = Instant.now();

    public Duration duration() {
       return Duration.between(start, Instant.now());

    public String toString() {
        Duration duration = duration();
        return String.format(formatter, duration.toHours()) + ":" + String.format(formatter, duration.toMinutes() % 60) + ":" + String.format(formatter, duration.getSeconds() % 60);

Duration class tease:



Edited by Botre
  • Like 2
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...