2014-10-18 103 views
0

我有两个变量 - 活动开始时间(currentTime)和单击按钮时间(endTime)。这些变量的值以毫秒为单位(System.currentTimeMillis())。我在布局中使用它们,所以我将这些值转换为DateFormat "HH:mm:ss"以毫秒为单位计算持续时间并将其转换为日期时间

我想currentTimeendTime之间计算时间durationTime),并将其转换成datetime。请看看我的代码:

public class MainActivity extends Activity { 

      long currentTime_ms, endTime_ms; 
      SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 

      @Override 
      public void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_main); 

       currentTime_ms = System.currentTimeMillis(); 
       Date currentTime = new Date(currentTime_ms); 
       currentTime_textView.setText(sdf.format(currentTime)); 
      } 

      public void btnOk_onClick(View v) { 

       endTime_ms = System.currentTimeMillis(); 
       Date endTime = new Date(endTime_ms); 
       Date durationTime = new Date(endTime_ms - currentTime_ms); 
      } 

     } 

最后我有错误时间。 (例如,我点击2 second后的按钮并获得durationTime02:00:02)。

你能帮我修复代码吗?或者也许还有其他的时间计算方法?

+0

首先你有坏onClickListener。当你有活动时,你必须设置监听按钮: 'Button btn =(Button)findViewById(R.id.button_id); btn.setOnClickListener(新OnClickListener { @覆盖 公共无效的onClick(){// 代码在这里 } }' – 2014-10-18 20:36:04

+0

好,感谢意见。我将使用OnClickListener。并且怎么样时间计算? – 2014-10-18 20:43:42

+0

它应该真的很简单,你有全局变量,所以它的好处,下面只是看看它的例子:http://stackoverflow.com/questions/21285161/android-difference-between-two-dates – 2014-10-18 20:45:52

回答

0

你可以得到当前时间SystemClock.elapsedRealtime();

  • 取两个时间戳(用于开始和结束),然后你就会有 两个不同的多头。
  • 计算它们之间的差异,并调用此函数,它将返回您正在查找的字符串。你可以自定义它,只要你想!

    public String toText(long difference) { 
        DecimalFormat df = new DecimalFormat("00"); 
    
        int remaining = (int) (difference % (3600 * 1000)); 
    
        int minutes = (int) (remaining/(60 * 1000)); 
        remaining = (int) (remaining % (60 * 1000)); 
    
        int seconds = (int) (remaining/1000); 
        remaining = (int) (remaining % (1000)); 
    
        int cents = (int) (((int) time % 1000)/10); 
    
        String text = ""; 
        text += df.format(minutes) + ":"; 
        text += df.format(seconds) + ":"; 
        text += df.format(cents); 
        return text; 
    } 
    

在你的情况,这应该返回"00:02:00":0分,2秒,0美分。

我希望这会有所帮助!

相关问题