Search code examples
javamilliseconds

How to format Milliseconds


In my code I'm getting milliseconds using

// elaspsed time in milliseconds
    public long getElapsedTime() {
        if (running) {
            return System.currentTimeMillis() - startTime;
        }
        return stopTime - startTime;
    }

As long is a whole number Where as I want to get the milliseconds in 00.0000 format However I've tried this so far

return ((System.currentTimeMillis() - startTime) / 1000f);

but I am not getting to particular format


Solution

  • It is not possible for you to set the return type to long and return a double or String value.

    However if you need to format a millisecond value to the provided format, you should be able to get it done using following code snippet.

    String.format("%d.%d",  TimeUnit.MILLISECONDS.toSeconds(millies),millies%1000);