发现此网站上的代码和此代码适用于我的情况,但有一种方法可以让我获得已用时间"持续时间"直接使用SimpleDateFormat格式化它(" HH:mm:ss")? 更具体一点..我想要这样的东西没有得到HH:mm:来自1970年的ss :) 例如:" 00:00:10"
SimpleDateFormat sdf = new SimpleDateFormat(" HH:mm:ss"); duration = endTime-startTime; durationStr = sdf.format(持续时间);
public long startTime;
public long endTime;
String durationStr;
public long durationSec;
public long minutes,seconds,hours;
@Override
public void onCreate(){
super.onCreate();
//service started
startTime = System.currentTimeMillis();
}
public getLastLocation(){
//this is where the service ends
endTime=System.currentTimeMillis();
Date d = new Date(endTime);
Date d1 = new Date(startTime);
duration = d.getTime() - d1.getTime();
durationSec = TimeUnit.MILLISECONDS.toSeconds(duration);
seconds = durationSec % 60;
durationSec/= 60;
minutes = durationSec % 60;
durationSec /= 60;
hours = durationSec % 24;
durationStr=String.valueOf(hours)+" "+String.valueOf(minutes)+" "+String.valueOf(seconds);
答案 0 :(得分:0)
你可以试试这个:
注意:我在这个例子中没有使用任何服务,所以我使用了postDelayed
,它在5秒后执行代码。基于此,我正在计算从活动开始到postDelayed
long delayedTime, currTime;
TextView text;
currTime = System.currentTimeMillis();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
delayedTime = System.currentTimeMillis();
text.setText("" + getDurationString((int)((delayedTime - currTime) * 0.001)));
}
}, 5000);
-
public String getDurationString(int seconds) {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = seconds % 60;
return twoDigitString(hours) + " : " + twoDigitString(minutes) + " : " + twoDigitString(seconds);
}
private String twoDigitString(int number) {
if (number == 0) {
return "00";
}
if (number / 10 == 0) {
return "0" + number;
}
return String.valueOf(number);
}