Domanda

This question may make confusion ,so i am explain it below.

I have already create a counter for counting the time(Like how much time people works).Its working fine with single characters (like 0:0:0), but i want to display it in decimal (like 00:00:00). I had tried the below code, but it works like the before .No changes yet.

  private void timer() {

    int locSec = 0;
    int locMin = 0;
    int locHr = 0;
    DecimalFormat format = new DecimalFormat("00");
    String formatSecond = format.format(locSec);
    String formatMinute = format.format(locMin);
    String formatHour = format.format(locHr);

    sec = Integer.parseInt(formatSecond);
    min = Integer.parseInt(formatMinute);
    hr = Integer.parseInt(formatHour);

    Timer T = new Timer();
    timeCounter = (TextView) findViewById(R.id.tvDisplayCountDown);
    T.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    timeCounter.setText("time= " + hr + ":"+ min + ":"+ sec);
                    sec++;
                    if(sec > 59){
                        sec = 0;
                        min = min + 1;                          
                    }
                }
            });
        }
    }, 1000, 1000);

}

where hr, min and sec are global variables and assigned as 0. But the output is same as before: 0:0:0

helps and suggestions are appreciable.

Thank You

È stato utile?

Soluzione

Check Here

Suppose formatSecond=01

    sec = Integer.parseInt(formatSecond); //this converts 01 to back 1 
    min = Integer.parseInt(formatMinute);
    hr = Integer.parseInt(formatHour);

Very Simple

First Change to final DecimalFormat format = new DecimalFormat("00");

Now use format.format(Double.valueOf(hr or min or sec))

So your code Should be:

timeCounter.setText("time= " + format.format(Double.valueOf(hr)) + ":" 
+format.format(Double.valueOf(min)) + ":"
+ format.format(Double.valueOf(sec)));

Output:

time=00:01:05 // As you Required

I have tested and working as per the Question's Requirement

Altri suggerimenti

You can use the below code:

    sec = Integer.parseInt(formatSecond);//eg:sec=5
    min = Integer.parseInt(formatMinute);//eg: min=9
    hr = Integer.parseInt(formatHour);//eg: hr=12

    System.out.format("%02d : %02d : %02d \n", hr,min,sec); //the output will be: 12 : 09 : 05

I hope the above code snippet has met your requirement.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top