File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Displaying seconds in hh:mm:ss format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Displaying seconds in hh:mm:ss format" Watch "Displaying seconds in hh:mm:ss format" New topic

Displaying seconds in hh:mm:ss format

Mark Herschberg

Joined: Dec 04, 2000
Posts: 6037
I have created a countdown timer, and I want to display the time left in my GUI. I would like it to be displayed as hh:mm:ss. I can't think of how to do this.
Date works as miliseconds since 1970. The GregorianCalendar stores a full date. If I could insure days won't be used (I'm not sure I can, but lets suppose for a moment), then maybe I could create a GregorianCalendar instance and use military time and set the time left as the time since midnight. Still, this seems wrong.
Does anyone know an easy way to do this, or do I need to write a special parser to convert seconds into my desired String format?
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

I just wrote this up really quick (and didn't test it), but it seems to me to be along the lines of what you want. (Come to think of it, you will need to add leading zeros to the minutes and seconds to display "12:06:09" instead of "12:6:9".) This seems a little easier than fiddling with Dates and DateFormat objects, given the fact that you (theoreticaly) could have an hours count of greater than 24 (You could display it as "124:45:15" or, by extending this to include days, display it at "5d 4:45:15" or whatever)
[ July 02, 2003: Message edited by: Joel McNary ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Mark Herschberg

Joined: Dec 04, 2000
Posts: 6037
Yeah, that's exactly what I wanted to avoid, because I'll have to deal with leading zeros and other such formatting annoyances. the nice thing about Date and Calendar is that there's a simple way to parse them.
Michael Matola
Ranch Hand

Joined: Mar 25, 2001
Posts: 1793
Maybe I'm missing something (this is the *advanced* forum after all) , but why not rely on some of the built-in time formatting?
Do you have a Date object already or are you working with the milliseconds? If you're working with milliseconds, does it bother you to create an intermediate Date object just to pass that to the formatter?

[ July 02, 2003: Message edited by: Michael Matola ]
I agree. Here's the link:
subject: Displaying seconds in hh:mm:ss format
It's not a secret anymore!