Jump to content

Timer snippet [Java 8]


Botre

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();
 t.duration().getSeconds();

Source:

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() {
        reset();
    }

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

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

    @Override
    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:

 

19e5cc39ddb7e3638ed7a724ad6785da.png

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

  • 1 year later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
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...