I'm making a stop watch where I'm using Java's SimpleDateFormat to convert the number of milliseconds into a nice "hh:mm:ss:SSS" format. The problem is the hours field always has some random number in it. Here's the code I'm using:
public static String formatTime(long millis) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss.SSS");
String strDate = sdf.format(millis);
return strDate;
}
If I take off the hh part then it works fine. Otherwise in the hh part it'll display something random like "07" even if the argument passed in (number of milliseconds) is zero.
I don't know much about the SimpleDateFormat class though. Thanks for any help.
Why not this ?
Variant: Up to 24 hours
Simple formatting for elapsed time less than 24h. Over 24h the code will only display the hours within the next day and won't add the elapsed day to the hours.
Missing features in sample code:
Variant: Over 24 hours
Using a plain Java
Calendar
for intervals up to one day (24 hours) see my answer to the question: How to format time intervals in Java?This one actually works, but it seems like I'm tweaking the intent of the method :-).
For those of you who really knows how this works you'll probably find some caveats.
Support for what you want to do is built in to the latest JDKs with a little known class called
TimeUnit
.What you want to use is java.util.concurrent.TimeUnit to work with intervals.
SimpleDateFormat
does just what it sounds like it does, it formats instances ofjava.util.Date
, or in your case it converts thelong
value into the context of ajava.util.Date
and it doesn't know what to do with intervals which is what you apparently are working with.You can easily do this without having to resort to external libraries like JodaTime.
The output will be formatted something like this
Reviewing the other answers, I came up with this function...