gpt4 book ai didi

android - 如何计算时间差并将结果显示在00 :00 format?

转载 作者:行者123 更新时间:2023-11-29 14:22:20 24 4
gpt4 key购买 nike

如何计算时间差并以 00:00 格式显示结果。我找不到方法,如何将字符串数据发送到日期以及如何以 EditText 00:00 格式显示结果。我自己试过了,但它显示找不到源的错误。下面是代码。

public class TimeCalculate extends Activity {

private String mBlock = null;
private String mBlockoff = null;
private String mBlockon = null;

Date date1,date2;
EditText block;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText blockoff = (EditText) findViewById(R.id.blockoff);
mBlockoff = blockoff.getText().toString();

EditText blockon = (EditText) findViewById(R.id.blockon);
mBlockon = blockon.getText().toString();
block = (EditText) findViewById(R.id.block);
mBlock = getDifference(date1, date2);

date1 = new Date(mBlockoff);
date2 = new Date(mBlockon);

blockon.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
block = (EditText) findViewById(R.id.block);
mBlock = getDifference(date1, date2);
block.setText(mBlock);
}

}

public static String getDifference(Date startTime, Date endTime) {
String timeDiff;
if (startTime == null)
return "[corrupted]";
Calendar startDateTime = Calendar.getInstance();
startDateTime.setTime(startTime);
Calendar endDateTime = Calendar.getInstance();
endDateTime.setTime(endTime);
long milliseconds1 = startDateTime.getTimeInMillis();
long milliseconds2 = endDateTime.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long hours = diff / (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
minutes = minutes - 60 * hours;
long seconds = diff / (1000);

timeDiff = hours + ":" + minutes;
return timeDiff;
}
}

我使用 SampleDateFormat 修改的代码

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");

try {
date1 = simpleDateFormat.parse(mBlockoff);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
date2 = simpleDateFormat.parse(mBlockon);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

然后我调用了下面的方法

blockon.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
mBlock = getDifference(date1, date2);
block.setText(mBlock);
}

最佳答案

其中一种方法可以是:
计算以毫秒为单位的差异,将其转换为秒,然后使用 DateUtils.elapsedTime(int sec) 将耗时格式化为 hh:mm 格式。

请参阅 DateUtils 的文档, Formatter .

编辑:示例代码:此函数将以 hh:mm:ss 格式返回时间

String getDifference(long now, long then){
if(now > then)
return DateUtils.formatElapsedTime((now - then)/1000L);
else
return "error";
}

关于android - 如何计算时间差并将结果显示在00 :00 format?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5163666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com