如何在时间设置上添加一小时但是SimpleDateFormat?

Wil*_*lNZ 0 java eclipse android simpledateformat

我有一个显示当前时间的开始按钮,我希望能够有一个停止时间比当前时间晚一个小时的按钮.我该怎么做呢?

这是显示当前时间的按钮的代码

Button stopButton = (Button) this
            .findViewById(R.id.StartTrackingEditStopTime_button);
    // using SimpleDateFormat class
    SimpleDateFormat sdfStopTime = new SimpleDateFormat("hh:mm:ss a",
            Locale.ENGLISH);
    String newStoptime = sdfStopTime
            .format(new Date(System.currentTimeMillis()));

    stopButton.append(newStoptime);
Run Code Online (Sandbox Code Playgroud)

非常感谢您提供有关如何执行此操作的任何帮助或建议.

Bri*_*son 6

您当前设置时间的方式new Date(System.currentTimeMillis())是采用精确的,当前的毫秒并从中确定日期.如果你坚持使用毫秒,你需要做的是增加一小时的毫秒或1000*60*60 = 3600000.

因此,您可以满足您的需求的方式#1是这个确切的代码:

Button stopButton = (Button) findViewById(R.id.StartTrackingEditStopTime_button);

SimpleDateFormat sdfStopTime = new SimpleDateFormat("hh:mm:ss a", Locale.ENGLISH);

String newStoptime = sdfStopTime.format(
        new Date(System.currentTimeMillis() + 3600000));

stopButton.setText(newStopTime);
Run Code Online (Sandbox Code Playgroud)

这会奏效.实现这一目标的方法#2,如果您系统地使用时间,则很有用,就是使用Calendar对象.为此,请使用以下代码替换上面的第三行:

Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, 1);
Date d = c.getTime();
String newStopTime = sdfStopTime.format(d);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!你的选择.