Print a string with hours,minute and seconds
Hi all,
a created a Thread which increments an attribute called seconds....it counts the number of seconds.
I would like to print on the screen a string with the following format : "hh:mm:ss"; step by step the string has to change for displaying the time.....the time has taken from the attribute of the seconds.
What is the most elegant way to do this ?
Cheers.
Stefano
[407 byte] By [
warxsga] at [2007-11-27 9:37:38]

The most elegant way to display seconds, if you are not insisting to print that field out, is new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
The most elegant way, in my opinion, would be to create a method in your Thread class that returns a String displaying the time according to its seconds attribute.
Perhaps overide toString?
Anyways...
public String toString() {
// perform calculation here
return hour + ":" + minute + ":" + seconds;
}
I'll repost when I finish the calculation... I'm trying to figure out how to get the numbers after the decimal in a double without using String parsing...
I don't mean to offend, but it seems redundant and makes no sense to override the functions already provided by Java itself.
If insist on calculating from that field, we can do
int seconds;
Calendar c = Calendar.getInstance();
c.setTimeInMillis(seconds);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(c.getTime()));
> The most elegant way to display seconds, if you are
> not insisting to print that field out, is
>
new
SimpleDateFormat("HH:mm:ss").format(Calendar.getInstan
ce().getTime());
The way I understand the OP, the request is not the current time (like 09:07:33 when the first reply in this thread was posted), but rather the current value of the seconds variable (like 0:07:11 when the same reply was posted if seconds were counted from when the original post was posted).
To convert a number of seconds to a hh:mm:ss string, use division and modulo operations. For instance (please correct any typos yourself):
int minutes = seconds / 60;
seconds = seconds % 60;
Same for hours.
Next, use a formatter to make sure a number after a colon is always printed woth 2 digits (0:7:11 looks silly, you want 0:07:11).
HTH
OleVVa at 2007-7-12 23:09:16 >
