1

現在の時刻が表示された開始ボタンがあり、現在の時刻より 1 時間後の停止時刻のボタンを使用できるようにしたいと考えています。どうすればこれを行うことができますか?

現在の時刻を表示するボタンのコードは次のとおりです

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);

これを行う方法についての助けやアドバイスをありがとう。

4

4 に答える 4

9

現在、時間を設定する方法はnew Date(System.currentTimeMillis())、正確な現在のミリ秒を取得し、それから日付を作成することです。どうしてもミリ秒単位で作業したい場合は、1 時間分のミリ秒を追加するか、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);

これは機能します。これを達成するための2番目の方法は、Calendar オブジェクトを使用することです。これを行うには、上記の 3 行目を次のコードに置き換えます。

Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR, 1);
Date d = c.getTime();
String newStopTime = sdfStopTime.format(d);

お役に立てれば!あなたの選択。

于 2012-09-19T02:27:38.763 に答える
2

これにより、すべてが SimpleDateFormat に保持されます。余分なオブジェクトを作成する必要はありません。

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

System.out.println("Before: " + sdfStopTime.getCalendar().getTime());

sdfStopTime.getCalendar().add(Calendar.HOUR, 1);

System.out.println("After: " + sdfStopTime.getCalendar().getTime());

add() メソッドの最初の引数はフィールド、時間、分などです。2 番目の引数は加算する量で、負の場合は減算します。

于 2012-09-18T23:54:57.077 に答える
1

Calendarクラス ( javadoc )を使用します。あなたがすでに持っていると仮定するとDate now

Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
calendar.add(Calendar.HOUR, 1);
Date inAnHour = calendar.getTime();

// format inAnHour with your DateFormat and set a button label
于 2012-09-18T23:48:43.797 に答える
0

現在の時刻に 1 時間を追加する必要があります。

// You don't have to put System.currentTimeMillis() to the constructor.
// Default constructor of Date gives you the current time.
Date stopTime = new Date();
stopTime.setHours(stopTime.getHours() + 1);
String newStoptime = sdfStopTime.format(stopTime);
stopButton.append(newStoptime);

setHours非推奨の関数およびを使用したくない場合は、 およびgetHoursを使用して、現在の時刻に 3,600,000 ミリ秒 (1 時間) を追加します。setTimegetTime

stopTime.setTime(stopTime.getTime() + 60 * 60 * 1000);

それ以外の

stopTime.setHours(stopTime.getHours() + 1);
于 2012-09-18T23:51:09.043 に答える