计算经过时间?

时间:2018-10-28 08:44:29

标签: java android time

我想知道如何实现这样的目标:

在活动B中,用户将键入一些内容,然后按一下按钮返回活动A。在活动A中,它将显示几秒钟前。如果状态是一个小时前,它将在一个小时前显示。

如何实现?

2 个答案:

答案 0 :(得分:1)

您可以这样做

 long startTime
 long duration

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startTime = SystemClock.uptimeMillis();
} 




 @Override
public void onBackPressed() {
    duartion = SystemClock.uptimeMillis() - startTime;
    //Duration you get in MS
    once you are done call 
    super.onBackPressed();//finish the activity

} 

答案 1 :(得分:0)

以下是不使用 java.time.LocalDateTime 的有效代码 如果您想使用它,可以进行必要的更改

您可以使用“共享”偏好设置来节省活动A中的时间。

为节省时间:

SharedPreferences preferences = null;
preferences = act.getSharedPreferences("your_name", Activity.MODE_PRIVATE);
preferences.edit().putString("TIME", getCurrentTimeDate())
.commit();

使用它来获取时间:

private String getCurrentTimeDate() {

    Calendar calendar = new GregorianCalendar();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    return formatter.format(calendar.getTime());
}

现在有2种解决方案可以继续:

  1. 将计时器设置为服务,它将继续在后台运行并不断更新时间

  2. 从SharedPreferences中检索数据,并在每次要显示值时计算差异。

根据您要显示此数据的次数选择选项

要计算活动B的差异:

    Calendar calendar = new GregorianCalendar();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    SharedPreferences shared = getSharedPreferences("your_name", MODE_PRIVATE);
    String saved_time = (shared.getString("TIME", ""));

    Date date = null,date2 = null;
    try {
        date = formatter.parse(saved_time);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    String currentTime = getCurrentTimeDate();
    try {
        date2 = formatter.parse(currentTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    printDifference(date,date2);

方法:在此活动中,也从上方使用了相同的getCurrentTimeDate

public void printDifference(Date startDate, Date endDate){

    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    System.out.println("startDate : " + startDate);
    System.out.println("endDate : "+ endDate);
    System.out.println("different : " + different);

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    //long elapsedDays = different / daysInMilli;
    //different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

    System.out.printf(
            "%d hours, %d minutes, %d seconds%n",
            elapsedHours, elapsedMinutes, elapsedSeconds);

}