0

Possible Duplicate:
How to convert milliseconds to “hh:mm:ss” format?

I bet many people need a timer consisting of: minutes : seconds : hundreds of seconds. Clearly you start with:

` public TimeGame(){

    timer = new Timer(10, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            counter++;
        }
    });
    timer.start();
}`

And then you need to call a methode that transforms this counter in : minutes : seconds : hundreds of seconds.

`private String timeTransfer(){

     minutes = counter/6000;
     counter = counter - (minutes*6000);
     seconds = counter/100 ;
     counter = counter - (seconds*100);
     milliseconds = counter;
     return minutes + " : " + seconds + " : " + miliseconds;
 }`

Yet i have a bug in my method. once it reaches 100 milliseconds it jumps back to 0. Normally it would have to put 0:1:0 , but it jumps back to 0:0:0. all Variables are declared private in the class.

So my question is does someone know a better method?

Community
  • 1
  • 1
MrMe TumbsUp
  • 416
  • 1
  • 4
  • 16

3 Answers3

5

Suggestions:

  • Besides your math being off, a basic timer rule: do not trust the time interval of a Timer, ever. Instead store the initial System time, subtract it from the current System time and base your calculations on the real time, not on some artificial counter increment.
  • Also, you're using magic numbers, and need to avoid them. Instead use constants such as SECONDS_PER_MINUTE and MINUTES_PER_HOUR which will help you avoid careless math errors.
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
4

Here is the cannonical form of this code, written many times by many people over many years:

private String timeTransfer(){

     minutes = counter/6000;
     seconds = (counter % 6000) /100 ;
     milliseconds = counter % 100;
     return minutes + " : " + seconds + " : " + milliseconds;
 }

Another poster commented that using the timer this way is inexact. If you are just running this thing for a couple of minutes, the errors won't add up too much. if you are doing more that a few minutes you will want to use the system time to handle this.

First you store the current time when you initialize your counter:

long startTime = System.currentTimeMillis();

Then you periodically update the counter from the start time just before you return from timeTransfer()

if (milliseconds < 10) {
    counter = (System.currentTimeMillis() - start) / 10;
}
Lee Meador
  • 12,221
  • 1
  • 29
  • 38
0

Your method timeTransfer() modifies class member variable counter. Copy it to local variable in the beginning of method and perform calculations on it, for example:

    long counter = this.counter;
Cozzamara
  • 1,268
  • 1
  • 13
  • 21