I am trying to make a stopwatch in android that includes hours and milliseconds. My chronometer always starts at 7:00:00.000 or in 24 hour format 19:00:00.000. Here is the code:
public class MainActivity extends Activity {
TextView tv;
long init,now,time;
@Override
public void onCreate(Bundle savedInstanceState) {
//...
myChronometer.setOnChronometerTickListener(new OnChronometerTickListener() {
public void onChronometerTick(Chronometer cArg) {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss.S");
now=System.currentTimeMillis();
time=now-init;
String s2 = timeFormat.format(time);
tv.setText(s2);
}
});
final ImageButton buttonStart = (ImageButton)findViewById(R.id.start);
buttonStart.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
init=System.currentTimeMillis();
myChronometer.setBase(init);
myChronometer.start();
}});
}
}
Is there anyway to start the chronometer at zero and continue the time from there?
Thank you
The 7 hour difference is likely due to your timezone. SimpleDateFormat uses your system’s timezone by default, whereas System.currentTimeMillis() gives you the time in UTC.
This should fix your problem, in onChronometerTick():
Notice I changed hh to H in your format string.