Jump to content

Timer snippet [Java 8]


Recommended Posts

Posted (edited)

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
  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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