如何在 android 中获得两个时差

How to get two time diffrences in android

在我的应用程序中有两个按钮。一个将显示开始时间,第二个将在单击时显示停止时间。我需要得到这两个值,计算差值并将其乘以另一个值。以下是我如何为其中一个标签设置值:

if (v == btnstart) {
    Toast.makeText(getApplicationContext(), "Work Start", Toast.LENGTH_LONG).show();
    Date d=new Date();

    SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
    String currentDateTimeString = sdf.format(d);
    txtstart.setText(currentDateTimeString);
}

当您单击 StartTime 按钮时,在 long 变量中使用 System.currentTimeMillis(); 获取时间,因为时间将以毫秒为单位,类似地,您可以在 StopTimer 按钮上执行相同的操作。 之后计算您将获得的两个时间之间的差异(以毫秒为单位)。 以防万一,如果您想将毫秒转换为秒,则将该值除以 1000。 希望对你有帮助。

您可以简单地使用 System.currentTimeMillis() 进行计算

if (v == btnstart) {
    Toast.makeText(getApplicationContext(), "Work Start", Toast.LENGTH_LONG).show();
//    Date d=new Date();

//    SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
//    String currentDateTimeString = sdf.format(d);
    startTime = System.currentTimeMillis();
    txtstart.setText(currentDateTimeString);
} else if (v == btnDone) {
    Toast.makeText(getApplicationContext(), "Work Done", Toast.LENGTH_LONG).show();
doneTime = System.currentTimeMillis();
takenTime = doneTime - startTime;
txtDone.setText(takenTime);
}

尝试

long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
long diff = end - start;
DateTime dt = new DateTime(diff);