Reputation: 539
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
Upvotes: 1
Views: 2946
Reputation: 106
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():
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.S");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
now=System.currentTimeMillis();
Notice I changed hh to H in your format string.
Upvotes: 4
Reputation: 1333
It seems to me that the chronometer use the current time as a start. You should probably not use
init=System.currentTimeMillis();
if you want to start a 0, but
init=0;
Hope this helps
Upvotes: 3