1

我正在尝试在 android 中制作一个包含小时和毫秒的秒表。我的计时器总是从 7:00:00.000 或 24 小时制 19:00:00.000 开始。这是代码:

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();
       }});

   }

}

有没有办法从零开始计时并从那里继续计时?谢谢

4

2 回答 2

4

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.

于 2012-12-14T18:31:04.780 回答
3

在我看来,计时器使用当前时间作为开始。您可能不应该使用

init=System.currentTimeMillis();

如果你想从 0 开始,但是

init=0;

希望这可以帮助

于 2012-12-14T18:00:27.440 回答