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.
Here's another way to do it. Fully self-contained and fully backwards-compatible. Unlimited number of days.
Here is what's going on. When you pass milliseconds, that number is relative to Jan 1st, 1970. When you pass 0, it takes that date and converts it to your local time zone. If you are in Central time then that happens to be 7PM. If you run this then it all makes sense.
Edit, I think what you want to do is get elapsed time. For this I recommend using JodaTime which already does this pretty well. You do something like
The format happens according to your local timezone, so if you pass 0, it assumes 0 GMT and then converts it in your local timezone.
A shorter way to do this is to use the DurationFormatUtils class in Apache Commons Lang:
Here's how I've done it, using only the standard JDK (this will work as far back as Java 1.1 by changing
StringBuilder
back toStringBuffer
):This is the first bit of Joda work I've done where it seemed more tedious than the JDK support. A Joda implementation for the requested format (making a few assumptions about zero fields) is: