質問

2009年1月1日に開始する必要があるプログラムがあり、新しい日を開始すると、私のプログラムは翌日表示されます。 これは私がこれまでに持っているものです:

GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy"); 
public void setStart()
{
    startDate.setLenient(false);
    System.out.println(sdf.format(startDate.getTime()));
}

public void today()
{
    newDay = startDate.add(5, 1);
    System.out.println(newDay);
//I want to add a day to the start day and when I start another new day, I want to add another day to that.
}

「newDay = startDate.add(5、1);」で、voidが見つかりましたが、エラーが見つかりました どうすればよいですか

役に立ちましたか?

解決

カレンダー オブジェクトには add メソッド。指定されたフィールドの値を加算または減算できます。

たとえば、

Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);

フィールドを指定するための定数は、「フィールドの概要」にあります。 Calendar クラス。

今後の参考のために、 Java API仕様には、 Java APIの一部であるクラスの使用方法に関する役立つ情報。


更新:

  

無効なエラーが見つかりましたが、   予想されるint、 'newDay =   startDate.add(5、1); '私は何をすべきか   

add メソッドは何も返さないため、 Calendar.add を呼び出した結果を割り当てようとしても無効です。

コンパイラエラーは、 int 型の変数に void を割り当てようとしていることを示します。 「何も」を割り当てることができないため、これは無効です。 int 変数に。

単なる推測ですが、おそらくこれは達成しようとしているものかもしれません:

// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);

// Get the current date representation of the calendar.
Date startDate = calendar.getTime();

// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);

// Get the current date representation of the calendar.
Date endDate = calendar.getTime();

System.out.println(startDate);
System.out.println(endDate);

出力:

Thu Jan 01 00:00:00 PST 2009
Fri Jan 02 00:00:00 PST 2009

考慮する必要があるのは、 Calendar が実際に何であるかです。

Calendar は日付の表現ではありません。これは、カレンダーの表現であり、現在指している場所です。カレンダーが現在指している場所の表現を取得するには、Calendar からhtml "rel =" noreferrer "> Date /docs/api/java/util/Calendar.html#getTime() "rel =" noreferrer "> getTime メソッド。

他のヒント

必要に応じてスイングできる場合は、日付/時刻のすべてのニーズをJODAに移動します。JODAははるかに優れたライブラリであり、ほぼすべてが不変であるという追加のボーナスがあります。つまり、マルチスレッドが無料で提供されます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top