0

Chronometer's ticking is working But when I try to get how much time elapses by using following formula.

%% SystemClock.elapsedRealtime() - cArg.getBase()

it adds 12 hours more (minute and second are precise)

it seems like I have to set time zone. But I don't know what I should do. plz help me.

private Chronometer jobTimerDisplay;
protected void onCreate(Bundle savedInstanceState) {
jobTimerDisplay = (Chronometer) findViewById(R.id.chronometer_Working);
jobTimerDisplay.start();
}


jobTimerDisplay.setOnChronometerTickListener(new OnChronometerTickListener() {
public void onChronometerTick(Chronometer cArg) {

         long t = SystemClock.elapsedRealtime() - cArg.getBase();
         sec.setText(DateFormat.format("ss", t));
         min.setText(DateFormat.format("mm", t));
         hour.setText(DateFormat.format("h", t));

        }});
user1979727
  • 117
  • 1
  • 8

1 Answers1

1

Chronometer.getBase() returns a long representing the UTC time of it's base - in your case, the time when the Chronometer was constructed.

This isn't your main problem, but for accuracy, you should probably invoke

 jobTimerDisplay.setBase(System.currentTimeMillis());

just before

jobTimerDisplay.start();

so that you reference the start time instead of the time when the Chronometer was constructed.

The real problem is that you are comparing the Chronometer's base time (which is an absolute point in time) to the length of time that the Android device has been running.

What you probably want is to compare the Chronometer's base time with the current time:

 long elapsedTime = System.getCurrentTimeMillis() - cArg.getBase();

Be aware that Dates in Java (and most languages) do not have timezones. Dates store their time as a long offset from the Java Epoch date, in UTC. You don't get a timezone until you format a Date, either by formatting it explicitly, or by explicitly or implicitly invoking it's toString() method, say by using it in a System.out.println statement.

Once you have that settled, you can proceed to deal with the fact that the DateFormat class doesn't format longs, it formats Dates (unless you have a custom DateFormat class, in which case, I'd suggest renaming it to avoid confusion).

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67